Selection Sort
Find the minimum element and place it at the front, repeat.
How it works
Selection Sort divides the array into two parts: a growing sorted region on the left and a shrinking unsorted region on the right. On each pass it scans the entire unsorted region to find the smallest element, then swaps that element into the first position of the unsorted region, extending the sorted region by one.
Unlike Bubble Sort, Selection Sort makes at most n−1 swaps regardless of the input, which can be useful when writes are expensive — for example, on EEPROM or flash memory where each write reduces the cell's lifespan. However, it always performs O(n²) comparisons even on a sorted array, so its best-case cost equals its worst case.
Selection Sort is not stable in its standard form: the swap can move an element past others with equal value, changing their relative order. An alternative linked-list implementation can be made stable, but the array version typically is not. It sorts in-place with O(1) auxiliary space.
Complexity
Visualizer
Where it's used in the real world
Embedded flash / EEPROM firmware
Sorting configuration records with minimal write cyclesFlash memory cells degrade with each write. Selection Sort's guarantee of at most n−1 swaps minimises the number of write operations compared to algorithms like Bubble Sort that may swap the same cell many times.
Card dealing / manual sorting processes
Simulation of human hand-sorting behaviourWhen humans sort a hand of cards by picking the smallest card and placing it first, they are executing Selection Sort. UI animations that mimic human card-sorting use this algorithm because the motion is intuitively recognisable.
Database query optimisers (worst-case bounding)
Cost estimation for small in-memory result setsFor very small n (typically ≤ 8), query planners sometimes fall back to simple O(n²) sorts because cache effects dominate: no pointer chasing, predictable branch patterns, and zero allocations beat the constant factors of merge sort or heap sort at this scale.
Implementation
function selectionSort(arr: number[]): number[] {
const a = [...arr];
const n = a.length;
for (let i = 0; i < n - 1; i++) {
let minIdx = i;
for (let j = i + 1; j < n; j++) {
if (a[j] < a[minIdx]) {
minIdx = j;
}
}
if (minIdx !== i) {
[a[i], a[minIdx]] = [a[minIdx], a[i]];
}
}
return a;
}
// Usage
console.log(selectionSort([38, 27, 43, 3, 9, 82, 10, 55]));
// [3, 9, 10, 27, 38, 43, 55, 82]