Intuition
Two people each hold a sorted stack of numbered cards. To combine them, keep comparing the top cards and take the smaller one. You never have to look further down either stack, so merging is fast.
Merge sort turns any list into that easy case: split it until every piece has one value (a list of one is sorted), then merge pieces back together, two at a time.
How it works
- If the range has one value or none, it’s sorted. Stop.
- Split the range at the middle and merge sort each half.
- Copy the two sorted halves aside.
- Repeatedly compare the front of each half and write the smaller value back into the array.
- When one half runs out, copy the rest of the other half.
Complexity
Each level of splitting merges n values in total, and halving n until pieces have one value takes about log₂ n levels. So merge sort makes about n log₂ n writes, whatever the input order. It never has a bad case, which is its big advantage over quicksort.
The cost is memory: merging needs a buffer as large as the range being merged, O(n) extra space.
Common mistakes
- Using
<instead of<=when merging. Taking from the right half on ties breaks stability. - Forgetting the leftovers. When one half is empty, the rest of the other half still has to be copied.
- Allocating a new buffer for every merge. It works, but one buffer reused across merges is much faster.
- Splitting at the wrong place. With
mid = (lo + hi) / 2, the halves arelo..midandmid + 1..hi. Usingmidin both repeats a value; skipping it loses one.
When to use it
When you need a stable sort or a guaranteed O(n log n) worst case, for linked lists (merging needs no random access), and for data too big for memory (external merge sort reads sorted chunks from disk).
Check yourself
Check yourself
Merging [1, 4, 9] with [2, 3, 10]: what is the 4th value written?
The merge writes 1, 2, 3, then 4. The full result is [1, 2, 3, 4, 9, 10].
Check yourself
How many levels of splitting does merge sort need for 16 values?
16 → 8 → 4 → 2 → 1: four halvings, log₂ 16 = 4.
Sources
- John von Neumann described merge sort in 1945; see Knuth, The Art of Computer Programming, Vol. 3, section 5.2.4.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, section 2.3, “Designing algorithms.”
Finished this page?
Your list