referrence: GeeksforGeeks
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
public static void SelectionSort ( int [ ] num )
{
int i, j, min, minIndex;
for ( i = 0; i < num.length; i++ )
{
min = num[i]; //initialize min
for(j = i; j < num.length; j ++) //inside loop
{
if( num[j] < min) {
min = num[j];
minIndex = j;
}
}
//swap min and num[i];
num[j] = num[i];
num[i] = min;
}
}
Time comlexity O(n^2), space cost O(1), and it is in-place sorting.