← capítulo

Merge sort

Split in half, sort each half, merge. The first O(n log n) sort — no bad case.

The merge is the trick

Watch runs merge and grow

12 runs of length 1 → 2 → 4 → 8 → sorted. Each green run is one merge.

O(n log n), guaranteed

T(n)=2T(n/2)+O(n)=O(nlogn)T(n) = 2T(n/2) + O(n) = O(n \log n)

No adversarial input — the split doesn't depend on the data.

The trade

Takeaway

Trade memory for a guarantee. The sort behind every stable library sort and every sort-a-file-too-big-for-memory. Next: quicksort.