Merge sort
medium 18 minMerge sort splits the array in half until every piece holds one value, then merges sorted pieces back together with two pointers.
Video lesson · Chapter 1 of 5
The two trays
Divide and conquer in 160 seconds
1:19Reel
How it works
Step through the idea, or press Play.
Divide. Split the range at the middle into a left half and a right half
Understand it
Start here
What merge sort is
Merge sort is a divide and conquer sort. It never tries to sort a big array directly. It cuts the array in half, sorts each half by cutting again, and keeps going until every piece holds a single value. A piece of one value is sorted by definition. Then it merges sorted pieces back together, two at a time, until one sorted array is left.
Divide
Find the middle and split into two halves. This costs : it is only index arithmetic.
Conquer
Sort each half recursively. The recursion stops at pieces of size 0 or 1.
Combine
Merge two sorted halves by repeatedly taking the smaller front value. This is where all the real work happens.
The picture
Split down, merge up
Take [38, 27, 43, 3, 9, 82, 10]. Splitting at the middle each time draws a tree going down; merging draws the same tree going back up. Values only change order on the way up.
The full divide and conquer tree for 7 values
| Level | Pieces | Sizes | What happens |
|---|---|---|---|
| 0 | 1 | 7 | the whole array |
| 1 | 2 | 4 and 3 | split at mid = 3 |
| 2 | 4 | 2, 2, 2, 1 | split again; [10] is already a base case |
| 3 | 7 | all 1 | single values, sorted by definition |
The merge step
Two sorted runs, two pointers
Merging is the heart of the algorithm. Both inputs are already sorted, so the smallest remaining value is always at the front of one of them. Point [i] at the front of the left run and [j] at the front of the right run, compare, take the smaller, and move that pointer on.
Merging left and right into a[lo..hi]
- 1Comparethe two front values
- 2Takethe smaller one into the output
- 3Advancethe pointer you took from
- 4Copy leftoverswhen one run is empty
Merging runs of sizes $p$ and $q$ costs at most $p + q - 1$ comparisons and exactly $p + q$ writes: linear time.
The algorithm
Divide, conquer, combine in code
The short version returns a new list. The base case is a list of length 0 or 1; everything else splits, recurses twice and merges.
def merge_sort(arr): if len(arr) <= 1: # base case: already sorted return arr mid = len(arr) // 2 # divide left = merge_sort(arr[:mid]) # conquer the left half right = merge_sort(arr[mid:]) # conquer the right half return merge(left, right) # combinedef merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # <= keeps equal values in order result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) # at most one of these result.extend(right[j:]) # two is non-empty return resultprint(merge_sort([38, 27, 43, 3, 9, 82, 10]))# [3, 9, 10, 27, 38, 43, 82]Worked example
Sorting [38, 27, 43, 3, 9, 82, 10]
- 1
Split the whole array
mid = (0 + 6) // 2 = 3: left[38, 27, 43, 3], right[9, 82, 10]. The recursion finishes the left half completely before it touches the right. - 2
Left half down to single values
[38, 27, 43, 3]splits into[38, 27]and[43, 3], then[38, 27]splits into[38]and[27]: two base cases. - 3
Merge [38] and [27]
, so 27 goes first:
[27, 38]. One comparison. - 4
Merge [43] and [3]
:
[3, 43]. One comparison. - 5
Merge [27, 38] and [3, 43]
take 3; take 27; take 38; left run empty, copy 43. Result
[3, 27, 38, 43]in three comparisons. - 6
Right half the same way
[9, 82]merges in one comparison ().[10]is a base case. Merging[9, 82]with[10]takes two:[9, 10, 82]. - 7
Final merge
[3, 27, 38, 43]with[9, 10, 82]: take 3, 9, 10, 27, 38, 43, then copy 82. Six comparisons. Result[3, 9, 10, 27, 38, 43, 82].
| Merge | Result | Comparisons |
|---|---|---|
| [38] + [27] | [27, 38] | 1 |
| [43] + [3] | [3, 43] | 1 |
| [27, 38] + [3, 43] | [3, 27, 38, 43] | 3 |
| [9] + [82] | [9, 82] | 1 |
| [9, 82] + [10] | [9, 10, 82] | 2 |
| [3, 27, 38, 43] + [9, 10, 82] | [3, 9, 10, 27, 38, 43, 82] | 6 |
| total | 6 merges | 14 |
The math
Deriving T(n) = 2T(n/2) + n
Let be the time to merge sort values. One call does three things: two recursive calls on halves, each costing , and one merge that touches all values once. Splitting is constant time. A piece of one value costs a constant.
The recurrence
Unroll it
Stop at size 1
The math
The recursion tree: n work on every level
Cost of each call in the recursion tree
Add up the levels
| n | |||
|---|---|---|---|
| 8 | 8 | 24 | 64 |
| 64 | 64 | 384 | 4,096 |
| 1,024 | 1,024 | 10,240 | 1,048,576 |
| 1,000,000 | 1,000,000 | about 20 million |
Complexity
Same time on every input, O(n) space
| Input (n) | Comparisons | Why |
|---|---|---|
| [38, 27, 43, 3, 9, 82, 10] (7) | 14 | runs interleave, every merge goes long |
| [1, 2, 3, 4, 5, 6, 7] sorted (7) | 11 | each merge stops when the left run empties |
| [1, 2, 4, 3, 5, 6, 7] nearly sorted (7) | 11 | one swapped pair barely changes anything |
| [7, 6, 5, 4, 3, 2, 1] reversed (7) | 9 | the right run empties first, after few comparisons |
| [4, 2, 7, 1] small (4) | 5 | 1 + 1 + 3 |
Comparisons in one merge
Head to head
Merge vs quick vs heap sort
| Property | Merge sort | Quick sort | Heap sort |
|---|---|---|---|
| Best time | |||
| Average time | |||
| Worst time | |||
| Extra space | stack | ||
| Stable | Yes | No | No |
| In place | No | Yes | Yes |
| Best use | Stability, linked lists, disk data | Fast general array sorting | Guaranteed time with no extra memory |
Which O(n log n) sort?
Why you cannot beat n log n by comparing
Variants
Bottom-up, linked lists and external sorting
Bottom-up
No recursion: merge runs of width 1, then 2, then 4, until one run covers the array. Same , no call stack.
Linked lists
Merging lists is just relinking nodes, so the extra array disappears. The go-to sort for linked lists.
External sorting
Data bigger than memory: sort chunks that fit, write them as runs, then merge the runs from disk.
Timsort
Finds runs already in order, extends short ones with insertion sort, then merges them. Python and Java use it.
def merge_sort_bottom_up(a): n, width = len(a), 1 while width < n: for lo in range(0, n, 2 * width): mid = min(lo + width, n) hi = min(lo + 2 * width, n) left, right = a[lo:mid], a[mid:hi] i = j = 0 k = lo while i < len(left) and j < len(right): if left[i] <= right[j]: a[k] = left[i]; i += 1 else: a[k] = right[j]; j += 1 k += 1 a[k:hi] = left[i:] + right[j:] width *= 2 return aprint(merge_sort_bottom_up([38, 27, 43, 3, 9, 82, 10]))# [3, 9, 10, 27, 38, 43, 82]External merge sort
sort command do this when data does not fit in memory. Merging reads each run front to back, which disks handle well.Pattern spotting
When to reach for it
Good for
- Large datasets where a guaranteed matters.
- Linked lists: no random access needed and no extra array.
- When a stable sort is required, such as sorting by one key after another.
- External sorting: data on disk that does not fit in memory.
- Problems that piggyback on the merge, like counting inversions.
Avoid when
- Memory is limited: it needs extra space.
- Arrays are small: recursion overhead loses to insertion sort.
- An in-place sort is required.
- Cache efficiency is critical: copying to temp arrays costs more than quick sort's in-place swaps.
Count inversions
While merging, each time a right value wins, it jumps over every value left in the left run. Add those up: .
Merge k sorted lists
The merge step with a heap: always take the smallest front among runs, .
Sort a linked list
Find the middle with slow and fast pointers, sort both halves, merge by relinking.
Recap
Key takeaways
Key points
- Divide at the middle, sort both halves recursively, merge them with two pointers. A piece of one value is the base case.
- Merging runs of size and costs at most comparisons and writes.
- unrolls to levels of work: in the best, average and worst case.
- extra space for the merge buffers plus stack. Not in place.
- Stable because ties take from the left run (
<=). - The best choice for linked lists, external sorting and stable sorting; Timsort is its practical descendant.