Selection Sort
General Algorithm
a. Iterates through the entire array in an outer loop. It initializes a minimum variable as the current value of i
.
b. Uses an inner loop starting from the first loop's index + 1. In this loop it looks for the lowest value.
c. Once it has completed the inner loop and found the lowest value, it compares that value to the current value of i
from the outer loop. If the minimum from the inner loop is less, then it is swapped with the value of i
from the outer loop.
It thus sequentially sorts an array in place. Swaps are kept to a minimum (N - 1
worst case) but compares are quadratic (N^2
).
int length = arr.length;
//
// Selection sort
//
// Progressivelly walk through the array
// This is the outer loop
for (int i = 0; i < length; i++) {
// establish the minimum as the current index
int min = i;
// Walk through the array starting from the outerloop + 1 since
// we want to check for a number that is lower in the rest of the array
// This is the inner loop
for (int j = i + 1; j < length; j++) {
// if the current minimum value is greater than the current array value in
// the inner loop, update the minimum
if (arr[j] < arr[min]) min = j;
}
// Make the swap if min is less than the current array element.
// You can have it swap every time but I needed to restrict it for my use case
if (arr[min] < arr[i]) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
return arr;