General description
The selection sort algorithm sorts an array by repeatedly searching for the minimum element (considering the ascending order) from the unsorted range and placing it at the beginning. The algorithm manages two sub-arrays in a given original array.
Code example
function selectionSort(array) {
// Loop over each element in array
for (let i = 0; i < array.length; i++) {
// store current min Index
let minIndex = i;
// for all upcoming elements, check if the current element is smaller then the min index
// if so, store the new minimal index
for (let j = i; j < array.length; j++) {
if (array[j] < array[minIndex]) minIndex = j;
}
// swap to the beginning of the unsorted array
if (array[minIndex] < array[i]) swap(array, minIndex, i);
}
return array;
}
// swap to given indexes
function swap(array, a, b) {
let temp = array[a];
array[a] = array[b];
array[b] = temp;
}
Explained
Basically, the Selection sort algorithm works by splitting an unsorted array into two parts (without actually creating a new array).
- first initialize a loop over all elements of the array
- find the minimum of the unsorted array
- set the minimum to the beginning of the unsorted array
- repeat the process for all upcoming elements, ignoring the already sorted values
Use cases
With a time complexity of O(n^2) it belongs to the slow sorting algorithms. It offers no real advantages over other sorting algorithms except for its simple and intuitive implementation.