Merge sort is the classic divide-and-conquer sort: split the array in half, sort each half recursively, then merge the two sorted halves into one. It runs in Θ(n log n) time on every input, it is stable, and it needs O(n) extra memory. Its predictable performance and sequential access pattern make it the backbone of Timsort, linked-list sorting and external sorting of datasets far larger than memory.
Think of it like
Merging two sorted stacks of exams
Two teaching assistants each hand you a stack of exams already sorted by student name. To combine them you only ever look at the top sheet of each stack, take whichever comes first alphabetically, and put it face down on your output pile. One glance per sheet and you are done. Merge sort simply keeps splitting the work until every "stack" has one exam, then merges its way back up.
How it works
- 1
Divide
Split
a[lo..hi]atmid = (lo + hi) / 2into a left half and a right half. - 2
Conquer
Recursively sort each half. A subarray of size 0 or 1 is already sorted: that is the base case.
- 3
Combine
Merge the two sorted halves into one sorted run using two pointers. All the real work happens here.
The merge procedure
Keep a pointer at the head of each sorted run. Repeatedly compare the two heads, copy the smaller one to the output and advance that pointer. When one run is exhausted, copy the rest of the other. Every comparison outputs one element, so merging runs with a combined length of n takes at most n − 1 comparisons and exactly n writes.
| Step | Left run | Right run | Compare | Output so far |
|---|---|---|---|---|
| 1 | [2, 5a, 9] | [1, 5b, 7] | 2 vs 1: take 1 | [1] |
| 2 | [2, 5a, 9] | [5b, 7] | 2 vs 5b: take 2 | [1, 2] |
| 3 | [5a, 9] | [5b, 7] | 5a vs 5b: tie, take left | [1, 2, 5a] |
| 4 | [9] | [5b, 7] | 9 vs 5b: take 5b | [1, 2, 5a, 5b] |
| 5 | [9] | [7] | 9 vs 7: take 7 | [1, 2, 5a, 5b, 7] |
| 6 | [9] | [] | right run empty: copy the rest | [1, 2, 5a, 5b, 7, 9] |
Top-down vs bottom-up
Top-down (recursive)
- Split at the middle and recurse, merge on the way back up
- Recursion depth ⌈log₂ n⌉, so O(log n) stack
- The most natural way to write and reason about it
Bottom-up (iterative)
- Merge runs of width 1, then 2, 4, 8, … until one run remains
- No recursion at all: ⌈log₂ n⌉ passes over the data
- Natural for linked lists, external sorting and GPUs
| Pass | Run width | Array after the pass |
|---|---|---|
| start | 1 | [38, 27, 43, 3, 9, 82, 10] |
| 1 | 2 | [27, 38, 3, 43, 9, 82, 10] |
| 2 | 4 | [3, 27, 38, 43, 9, 10, 82] |
| 3 | 8 | [3, 9, 10, 27, 38, 43, 82] |
[10] in pass 1) is simply carried forward.Solving the recurrence
Draw the recursion tree. Level k has 2ᵏ subproblems of size n/2ᵏ, and merging them costs cn in total at every level. Halving from n down to 1 takes log₂ n steps, so there are log₂ n + 1 levels.
| Level | Subproblems | Size of each | Merge cost at this level |
|---|---|---|---|
| 0 | 1 | n | cn |
| 1 | 2 | n/2 | cn |
| 2 | 4 | n/4 | cn |
| k | 2ᵏ | n/2ᵏ | cn |
| log₂ n | n | 1 | cn |
Counting comparisons exactly: the worst case is n⌈log₂ n⌉ − 2^⌈log₂ n⌉ + 1, which is n log₂ n − n + 1 when n is a power of two, very close to the information-theoretic minimum of log₂(n!). On already-sorted input each merge stops comparing as soon as the left run is exhausted, giving about (n/2) log₂ n comparisons. The plain algorithm still takes Θ(n log n) time there, because every element is copied at every level, unless you add the skip check described below.
Stability and space
Merge sort is stable (ties take from the left run) but not in-place: merging needs an auxiliary buffer of up to n elements, plus O(log n) stack for the top-down version. In-place merging is possible but intricate; simple in-place schemes based on rotations cost O(n log² n), which is what C++ std::stable_sort falls back to when it cannot allocate a buffer.
- Allocate the buffer once and pass it down, instead of allocating new arrays in every call.
- Skip sorted merges: if
a[mid - 1] <= a[mid], the halves are already in order and the merge can be skipped. Sorted input then runs in O(n). - Cut off small subarrays: switch to Insertion Sort below roughly 16 to 32 elements to avoid recursion overhead.
- Ping-pong buffers: alternate the roles of the array and the buffer between levels to avoid copying back after every merge.
Merge sort on linked lists
Linked lists are merge sort's natural habitat. Merging two lists needs no extra memory: you just relink next pointers. The middle can be found with the Fast & Slow Pointers technique. Quick sort and heap sort, by contrast, rely on random access that Linked Lists cannot provide efficiently.
Arrays
- O(n) auxiliary buffer for merging
- Splitting is O(1) index arithmetic
- Usually beaten by quick sort in practice
Linked lists
- Merge by relinking: O(1) extra space per merge
- Splitting costs O(n) per level, which does not change O(n log n)
- The best general-purpose list sort (GNU
std::list::sortis a merge sort)
External sorting
What if the data does not fit in memory? Merge sort only needs to read its runs sequentially, which is exactly what disks and network storage do well. External merge sort has two phases.
- 1
Run generation
Read as much data as fits in RAM, sort it in memory, and write it out as a sorted run. Repeat until the input is consumed.
- 2
k-way merge
Open all runs at once with a small read buffer each. Keep the current head of every run in a min-heap (Heaps & Priority Queues): pop the smallest, write it out, and push the next element from the same run. Each output element costs O(log k).
- 3
More passes if needed
If there are too many runs to buffer at once, merge them in groups and repeat. With modern memory sizes one merge pass is almost always enough.
Data
1 TB
far larger than memory
RAM
10 GB
per sorted run
Runs
100
merged in one 100-way pass
I/O
2 reads + 2 writes
of every byte, all sequential
Databases use this when an ORDER BY or sort-merge join spills to disk, the Unix sort command uses it for large files, and the shuffle phase of MapReduce-style systems is a distributed external merge sort.
Counting inversions
An inversion is a pair i < j with a[i] > a[j]. Counting them by brute force is O(n²), but merge sort can count them for free. During a merge, when an element from the right run is output while mid − i elements remain in the left run, each of those remaining elements is larger than it and comes earlier: that is mid − i inversions at once.
def count_inversions(a: list[int]) -> int:
def sort(lo: int, hi: int) -> int: # sorts a[lo:hi], returns its inversions
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
count = sort(lo, mid) + sort(mid, hi)
merged, i, j = [], lo, mid
while i < mid and j < hi:
if a[i] <= a[j]:
merged.append(a[i])
i += 1
else:
merged.append(a[j])
j += 1
count += mid - i # a[j] is smaller than all of a[i:mid]
merged += a[i:mid] + a[j:hi]
a[lo:hi] = merged
return count
return sort(0, len(a))
print(count_inversions([2, 4, 1, 3, 5])) # 3: (2,1), (4,1), (4,3)Merge sort in the real world: Timsort
Real data is rarely random: it often contains already-sorted stretches. Timsort (Tim Peters, 2002) is a merge sort built for that. It scans for natural runs (reversing descending ones), extends short runs to a minimum length with binary insertion sort, and merges runs from a stack whose size invariants keep merges balanced. When one run keeps winning, it switches to galloping (exponential search) to copy large blocks at once.
| Property | Timsort |
|---|---|
| Best case | O(n) on already-sorted or reverse-sorted input |
| Worst case | O(n log n) |
| Stable | Yes |
| Used by | Python sorted and list.sort, Java Arrays.sort for objects, Android, V8's Array.prototype.sort |
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Best | O(n log n) | O(n) | O(n) with the `a[mid - 1] <= a[mid]` skip on sorted input |
| Average | O(n log n) | O(n) | Every level does Θ(n) merge work |
| Worst | O(n log n) | O(n) | At most n⌈log₂ n⌉ − 2^⌈log₂ n⌉ + 1 comparisons |
| Linked list | O(n log n) | O(log n) | Merging relinks nodes; only the recursion stack |
| External (k-way) | O(n log n) | O(M) | M = memory budget; each byte read and written about twice |
Stable and not in-place. Top-down recursion adds O(log n) stack.
Implementation
Recursive, half-open ranges, one auxiliary buffer reused by every merge, and a skip when the halves are already in order.
def merge_sort(a: list[int]) -> list[int]:
buf = a[:] # one auxiliary buffer, reused
def merge(lo: int, mid: int, hi: int) -> None:
buf[lo:hi] = a[lo:hi]
i, j = lo, mid
for k in range(lo, hi):
if i < mid and (j >= hi or buf[i] <= buf[j]): # <= keeps it stable
a[k] = buf[i]
i += 1
else:
a[k] = buf[j]
j += 1
def sort(lo: int, hi: int) -> None: # sorts a[lo:hi]
if hi - lo <= 1:
return
mid = (lo + hi) // 2
sort(lo, mid)
sort(mid, hi)
if a[mid - 1] <= a[mid]: # halves already in order
return
merge(lo, mid, hi)
sort(0, len(a))
return aKey takeaways
- Merge sort splits in half, sorts each half recursively and merges: T(n) = 2T(n/2) + n = Θ(n log n) on every input.
- Merging two sorted runs with two pointers costs at most n − 1 comparisons; taking from the left on ties makes the sort stable.
- It needs O(n) auxiliary space on arrays, but only relinking (no buffer) on linked lists.
- Its sequential access pattern makes it the basis of external sorting: sorted runs plus a k-way merge with a min-heap.
- A merge step can count inversions in O(n log n), and Timsort turns merge sort into an adaptive, real-world workhorse.
Common pitfalls
- Using
<instead of<=in the merge, which takes equal elements from the right run first and breaks stability. - Allocating new arrays in every recursive call (or slicing in Python), which adds heavy allocation overhead and O(n log n) total garbage.
- Computing the midpoint of a linked list with
fast = headinstead ofhead.next, which never splits a two-node list and recurses forever. - Forgetting to copy the remainder of the non-empty run after the main merge loop.
Interview tips
- Derive the recurrence and the recursion-tree argument out loud; interviewers often ask why it is n log n and not just what it is.
- For "sort a linked list in O(n log n)", merge sort is the expected answer; mention O(1) extra space with the bottom-up version.
- Recognize merge-and-count problems: inversions, reverse pairs, count of smaller numbers after self and count of range sum all reuse the merge step.
Real-world applications
- Stable sorting in standard libraries (Timsort in Python and Java,
std::stable_sortin C++). - External sorting in databases, the Unix
sortutility and MapReduce shuffles. - Sorting linked lists without extra memory.
- Counting inversions to compare rankings (Kendall tau distance) and in collaborative filtering.
Practice problems
Test yourself
What does the recurrence T(n) = 2T(n/2) + Θ(n) solve to?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.