Intuition
Picture lining up a class by height. You scan the whole group for the shortest person and send them to the front. Then you scan everyone who’s left for the next shortest, and so on. Each scan finishes one spot for good, and you never revisit it.
How it works
- Start at index 0. Assume the value there is the smallest.
- Compare it with every value to its right. Whenever one is smaller, remember that one instead.
- At the end of the pass, swap the smallest value into index 0. That position is now final.
- Move to index 1 and repeat. Stop when one value is left; it is already in place.
The grey bar in the figure is the “smallest so far”. Watch it jump each time a comparison finds something smaller.
Complexity
| Case | Comparisons | Swaps |
|---|---|---|
| Best (sorted) | n(n − 1)/2 | 0 |
| Average | n(n − 1)/2 | about n − 1 |
| Worst | n(n − 1)/2 | n − 1 |
The comparison count is fixed: the first pass checks n − 1 values, the next n − 2, and so on down to 1. Unlike insertion sort and bubble sort, it gets no faster on sorted or nearly sorted input. What it saves is swaps: one per pass at most, against up to n²/2 for the other two.
Why it isn’t stable
The long-distance swap can jump a value over an equal one. Sort [4a, 4b, 1]: the first pass swaps 1 with 4a, giving [1, 4b, 4a]. The two 4s have changed order. If you sort records by one field after another, that matters; use a stable sort like merge sort instead.
Common mistakes
- Swapping inside the inner loop. Swapping every time a smaller value turns up still sorts, but turns the few swaps into many. Remember the index and swap once at the end of the pass.
- Comparing with the wrong value. Compare each value with the smallest found so far,
a[smallest], not witha[i]. - An extra pass. The outer loop can stop at n − 2; the last value has nowhere else to go.
When to use it
Almost never in production: use the built-in sort. Selection sort is worth knowing because it’s the simplest sort to reason about, it does the fewest writes, and its “pick the smallest, then repeat” idea is exactly what heap sort speeds up with a heap.
Check yourself
Check yourself
How many swaps does selection sort make on [1, 2, 3, 4, 5]?
Each pass finds that the smallest value is already at the front, so nothing moves. It still makes 4 + 3 + 2 + 1 = 10 comparisons to find that out.
Check yourself
After two passes over [5, 3, 8, 1, 4], what does the list look like?
Pass 1 swaps 1 into index 0: [1, 3, 8, 5, 4]. Pass 2 finds 3, already at index 1, so nothing moves.
Sources
- Donald Knuth, The Art of Computer Programming, Vol. 3, section 5.2.3, “Sorting by selection.”
- Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition, section 2.1, “Elementary sorts.”
Finished this page?
Your list