Codele / Algorithms
Merge sort
A huge pile of exam papers is hard to sort. Cut it in half, hand the halves to helpers, and then join the sorted halves back together. Cutting is easy; joining is the clever part.
- Merge sort cuts the pile in half again and again, down to piles of one card, which are already sorted.
- To merge two sorted piles, repeatedly take the smaller of the two front cards. The new pile comes out sorted.
- Our code works bottom-up: merge piles of 1, then of 2, then of 4, doubling the width each level. This simple version needs 2, 4, 8, 16... cards.
- The piles can only be cut about log n times, and each level of merging touches every card once: about n times log n steps, written O(n log n).
- The price: it needs extra room for the new piles.
Loading the playable lesson…