Kolton Ndoj

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. 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. 2. Merge pairs of sorted pieces by repeatedly taking the smaller front item.
  3. 3. Keep merging until one sorted list remains.
  4. 4. Quicksort instead: pick a pivot, partition into 'smaller' and 'bigger' piles, and recursively sort each pile.

The key formula

n2  vs.  nlog⁡2nn^2 \;\text{vs.}\; n\log_2 n
n2n^2
naive sorts like bubble sort: compare (nearly) every pair
nlog⁡2nn\log_2 n
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

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.

Related

Open it in the Math Lab →

Theory · Beginner-friendly