Let's now see the Java implementation of Selection sort algorithm based on the pseudocode discussed in the previous segment. Please download the java file below for your reference.
Now let us take a look at a simple code implementation for selection sort. So here my sorting function is going to take an input element input array, and it's going to declare a variable n, which equals to the length of the array. Now, here I'll run a for loop where my iterator I starts from zero and goes till n minus one. Now, as discussed in the pseudocode, we'll declare another variable min, which we'll initialize as i. After doing that, we'll run a for loop. In this for loop, I'm going to start my iterator j from I plus one. This J will go till n. And if at any point it finds that array of j is less than array of min, then it will update the min value to the jth index. After this process is over, we are going to simply swap array of min with array of i. That is, I am storing array of min in a temp. Then array of min is getting assigned the value of array of i. And finally, array of I is getting assigned the value of temp. So these three steps ensure my swapping. So let us now run this code and check out. So, I tried to run this code on this input array, which is clearly unsorted. And what is the result which I got? Well, here on the output console, this same array is getting printed in the sorted order. So this is how selection sort works.
Selection sort is a simple sorting algorithm
Sorting function takes an input element input array
Declare variable equals to the length of the array
Run a for loop where iterator starts from zero and goes till minus one
Declare another variable min, which is initialized as
Run another for loop where iterator starts from i plus one and goes till
If at any point array of is less than array of min, then update the min value to the jth index
After the process, swap array of min with array of by storing array of min in a temp, assigning array of min the value of array of , and finally, assigning array of the value of temp
Running the code sorts the input array in ascending order
This is how selection sort works.
We are done with Selection sort algorithm, it's pseudocode and it's Java implementation as well. In the next segment you will learn how efficient the algorithm is.