Five algorithms · One problem · Press play
Every list wants to be sorted. The question is how many moves it takes to get there. This is a hands-on tour of the five sorting algorithms every programmer should know — run them, step through them, race them.
fig. 6 — head-to-head trial
Same shuffled list, five contenders, one operation per tick each. Big-O notation stops being abstract the moment you watch merge and quick sort lap the quadratic field. Place your bets, then press start.
* Each tick advances every algorithm by exactly one primitive operation (a comparison or a write), so the finish order reflects total work done — not wall-clock trickery. With 45 items, the quadratic sorts need roughly 1,000–2,000 operations; the divide-and-conquer pair needs a few hundred.
fig. 7 — comparative anatomy
Clip and save. n is the number of items; complexities count comparisons and moves as the list grows.
| Algorithm | Best | Average | Worst | Space | Stable | Reach for it when… |
|---|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | You're teaching, or the list is tiny and nearly sorted. Otherwise, almost never. |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No | Writes are expensive (flash memory) — it makes at most n−1 swaps. |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | Small or nearly-sorted data. It's the finishing move inside real-world hybrid sorts. |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes | You need guaranteed speed and stability — linked lists, external sorting, Timsort's backbone. |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No | General-purpose in-memory sorting. Superb cache behavior; the worst case is rare with random pivots. |