Selection sort divides the array into a sorted prefix and an unsorted suffix. Each round: scan the whole unsorted region to find its minimum, then swap that minimum with the region's first element. The sorted prefix grows by one; the unsorted region shrinks by one. After n-1 rounds, done.
The interesting property is the swap count: exactly one swap per round, at most n-1 total, the fewest of any classic O(n²) sort. Comparisons, though, are unbudgeable: each round scans everything remaining, n-1 + n-2 + ... + 1 ≈ n²/2 total, regardless of the input's order. Already-sorted input costs the same comparisons as reversed input.
Implementation
// Pure: returns a new sorted array. NOT stable (long-distance swaps).
function selectionSort(input) {
const arr = [...input];
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIdx = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) minIdx = j; // track, don't move
}
if (minIdx !== i) {
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]]; // exactly one swap
}
}
return arr;
}| Operation / case | Cost | Notes |
|---|---|---|
| Comparisons (any input) | O(n²) | always ~n²/2, order doesn't matter |
| Swaps | O(n) | ≤ n−1: its signature strength |
| Space | O(1) | in-place |
| Stable? | No | long-distance swaps reorder equal keys |