Selection sort
Quote
“It's hardware that makes a machine fast. It's software that makes a fast machine slow.” — Craig Bruce
Case | Time complexity | Space complexity |
---|---|---|
Best | \(\color{white} \fcolorbox{crimson}{firebrick} {Ω(n^2)}\) | |
Average | \(\color{white} \fcolorbox{crimson}{firebrick} {Θ(n^2)}\) | |
Worst | \(\color{white} \fcolorbox{crimson}{firebrick} {O(n^2)}\) | \(\color{white} \fcolorbox{limegreen}{forestgreen} {O(1)}\) |
Selection sort is easy to implement but performs the worst of them all.
function selectionSort(array: number[]): void {
for (let step = 0; step < array.length - 1; step++) {
let minIndex = step;
for (let i = step + 1; i < array.length; i++) {
if (array[i] < array[minIndex]) {
minIndex = i;
}
}
let temp = array[step];
array[step] = array[minIndex];
array[minIndex] = temp;
}
}
Use cases¶
- The list to sort is small
- It needs to check all elements
- Swapping elements is okay