Sorting: merge sort and quicksort
Every time a leaderboard ranks scores, a shop sorts by price, or your files line up A to Z
What problem does it solve?
How do you put a million things in order without comparing every pair?
The big idea
Comparing every pair takes about n² steps, which for a million items is a trillion. The trick is divide and conquer: merging two piles that are already sorted is easy (just keep taking the smaller top card), so sort small piles and merge them up. Quicksort flips it around: pick a 'pivot', throw everything smaller to the left and bigger to the right, then sort each side. Either way you do about log₂ n rounds of n work each.
How it works, step by step
- 1. Merge sort: split the list in half, again and again, until every piece has one item (a one-item list is already sorted).
- 2. Merge pairs of sorted pieces by repeatedly taking the smaller front item.
- 3. Keep merging until one sorted list remains.
- 4. Quicksort instead: pick a pivot, partition into 'smaller' and 'bigger' piles, and recursively sort each pile.
The key formula
- naive sorts like bubble sort: compare (nearly) every pair
- merge sort always, quicksort on average: log₂ n levels of halving, n work per level
How fast is it?
For n = 1,000,000: n² is 10¹², but n log₂ n is about 2×10⁷, which is 50,000 times less work. There's a proven floor too: any sort that only compares items needs at least log₂(n!) ≈ n log₂ n comparisons in the worst case. Quicksort's unlucky worst case is n², which is why real libraries add safeguards.
Try it yourself
- Sort a shuffled deck of cards by merge sort with a friend: each of you sorts half, then merge.
- Why does sorting help binary search? How many sorts are worth it if you'll search a million times?
Fun fact
The sort built into Python (and used by Java for objects) is Timsort, invented by Tim Peters in 2002. It is a merge sort hybrid that hunts for already-sorted runs in real data, because real data is rarely truly random.