function selectionSort(array: number[]) { for (let i = 0; i < array.length - 1; i++) {let minIndex = i;
for (let j = i + 1; j < array.length; j++) {if (array[j] < array[minIndex]) minIndex = j;
}
if (minIndex !== i) [array[i], array[minIndex]] = [array[minIndex], array[i]];
}
}
Start: 24 values. Each pass finds the minimum of the rest and swaps it to the front.
Understanding Selection sort
The idea
Selection sort splits the array into a sorted prefix and the rest. On each pass it scans the rest for the minimum and swaps it into the first unsorted position. After pass i the prefix of length i + 1 is final, and nothing in it ever moves again.
The scan is what costs: finding the minimum of k elements takes k − 1 comparisons, and the passes add up to n²/2 comparisons regardless of the input. The swap count is the flip side: at most one per pass, n − 1 in total.
The four stages
Complexity
Versus its siblings
Pseudocode
SELECTIONSORT(array)
for i ← 0 to n − 2
minIndex ← i
for j ← i + 1 to n − 1
if array[j] < array[minIndex]: minIndex ← j
swap array[i], array[minIndex]
When to use
Pitfalls
History
Selection sort is old enough to have no single inventor; it appears in the earliest sorting surveys of the 1950s as the obvious way to sort by hand. Its lasting niche is hardware with a limited number of writes, and it is the sort behind heap sort once the scan is replaced by a heap.