Selection sort: the idea
Prerequisites: Arrays, comparisons, and tracking a minimum.
Selection sort separates an array into a settled prefix and an unsorted remainder. It scans the entire remainder to find its smallest item, then swaps that item into the next prefix position. A new scan begins for the next slot. Even an already sorted array still needs these scans.
Try it on the same input
Choose Repeated values and track the original-position labels on equal values. A long-distance swap can reverse their order. On Already sorted, notice that comparisons still accumulate even though no swaps are necessary.
Time, memory, and stability
n is the number of input items. Best, average, and worst O(n²). O(1) auxiliary space; at most n − 1 swaps.
A stable sort preserves the original order of items whose values are equal. This implementation is not stable. Identity labels record each item’s initial position. An unstable algorithm can preserve equal-item order on a particular input; it makes no guarantee for all inputs.
These bounds describe the sorting algorithm itself. The visualization saves a copy of the array at every operation for reversible playback, so recording uses additional time and memory. Its input size is capped at 24 items.
When to use it—and what to watch
Few swaps can be useful when writes are expensive, but the quadratic number of comparisons remains. This swapping version does not preserve equal items’ original order.
Reading the display
Comparisons count tests between item values. A swap writes two array positions; a merge write updates one. The counters exclude copying merge buffers, index tests, and playback work, so they are teaching measurements rather than elapsed-time benchmarks. Green marks final positions; a highlighted range indicates current work. For recursive algorithms, depth counts the active call levels.
Continue exploring
- Bubble sort — Compare neighbors and let large values travel to the right.
- Insertion sort — Grow a sorted prefix by moving each new item into place.
- Merge sort — Sort two halves, then weave their values into one ordered sequence.
- Quicksort — Partition around a pivot, then sort the ranges on either side.