Merge Sort
Split down to singletons, merge back up in order, the O(n log n) guarantee in action.
Split down to singletons, merge back up in order, the O(n log n) guarantee in action.
step 1 / 43
What's happening
Merge sort: split the array in half recursively, then merge sorted halves. Guaranteed O(n log n), watch the halves merge back in order.
The highlighted range is the sub-array currently being merged. Values stream from a side buffer (✎ writes), that buffer is the O(n) space cost.
Understand the algorithm
What it is
Merge sort splits the array down to single elements and merges the halves back together in order, divide and conquer with a guaranteed O(n log n).
Why it matters
It is the canonical divide-and-conquer algorithm and the standard proof that O(n log n) sorting is always achievable. Its merge step (two sorted stacks, one output) is one of the most reused primitives in computing, external sorting, database joins, and interval merging all reduce to it.
How it works
- 1Split the array into two halves.
- 2Recursively sort each half (single elements are trivially sorted).
- 3Merge: repeatedly take the smaller front element of the two halves into the output.
- 4The recursion depth is log₂ n; each level does O(n) merge work.
Real-world uses
- Stable sorting in standard libraries (Timsort = merge + insertion)
- External sorting of data too big for memory
- Counting inversions; database merge joins
- Sorting linked lists efficiently (O(1) extra space there)
Strengths
- Guaranteed O(n log n), no adversarial input
- Stable, equal elements keep their order
- Predictable, parallelizes naturally
Limitations
- O(n) auxiliary buffer, the price of the guarantee
- Slower than tuned quick sort in cache-resident workloads
- Recursion overhead for tiny inputs (fixed by the insertion-sort handoff)
Go deeper
The highlighted range shows which sub-array is being merged.