AlgoViz

Merge sort

medium 18 min

Merge 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

0:00 / 4:16

Divide and conquer in 160 seconds

1:19Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

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 O(1)O(1): 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

Top half: the divide phase, all splitting and no comparing. Bottom half: the merge phase, where every comparison happens.
LevelPiecesSizesWhat happens
017the whole array
124 and 3split at mid = 3
242, 2, 2, 1split again; [10] is already a base case
37all 1single values, sorted by definition
Halving 7 down to 1 takes ⌈log⁡27⌉=3\lceil \log_2 7 \rceil = 3 levels. Each level holds all nn values between its pieces.

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]

Each trip round the loop makes one comparison and writes one value. When one run empties, the other is copied as it is.
The merge in four beats
  1. 1Comparethe two front values
  2. 2Takethe smaller one into the output
  3. 3Advancethe pointer you took from
  4. 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.

Python
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]
Top-down merge sort. Two recursive calls, then one linear merge.
Edit and run it in your browser

Worked example

Sorting [38, 27, 43, 3, 9, 82, 10]

  1. 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. 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. 3

    Merge [38] and [27]

    27<3827 < 38, so 27 goes first: [27, 38]. One comparison.

  4. 4

    Merge [43] and [3]

    3<433 < 43: [3, 43]. One comparison.

  5. 5

    Merge [27, 38] and [3, 43]

    3<273 < 27 take 3; 27<4327 < 43 take 27; 38<4338 < 43 take 38; left run empty, copy 43. Result [3, 27, 38, 43] in three comparisons.

  6. 6

    Right half the same way

    [9, 82] merges in one comparison (9<829 < 82). [10] is a base case. Merging [9, 82] with [10] takes two: [9, 10, 82].

  7. 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].

MergeResultComparisons
[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
total6 merges14
Six merges for seven values: every merge glues two pieces into one, so nn pieces need exactly n−1n - 1 merges.

The math

Deriving T(n) = 2T(n/2) + n

Let T(n)T(n) be the time to merge sort nn values. One call does three things: two recursive calls on halves, each costing T(n/2)T(n/2), and one merge that touches all nn values once. Splitting is constant time. A piece of one value costs a constant.

The recurrence

T(n)=2 T ⁣(n2)⏟sort both halves+c n⏟merge,T(1)=cT(n) = \underbrace{2\,T\!\left(\tfrac{n}{2}\right)}_{\text{sort both halves}} + \underbrace{c\,n}_{\text{merge}}, \qquad T(1) = c
We take nn to be a power of 2 so the halves are exact; rounding does not change the answer.

Unroll it

T(n)=2T ⁣(n2)+cn=4T ⁣(n4)+cn+cn=8T ⁣(n8)+3cn=2k T ⁣(n2k)+k cn\begin{aligned} T(n) &= 2T\!\left(\tfrac{n}{2}\right) + cn \\ &= 4T\!\left(\tfrac{n}{4}\right) + cn + cn \\ &= 8T\!\left(\tfrac{n}{8}\right) + 3cn \\ &= 2^{k}\,T\!\left(\tfrac{n}{2^{k}}\right) + k\,cn \end{aligned}
Each expansion doubles the number of subproblems, halves their size, and adds one more cncn.

Stop at size 1

n2k=1  ⟺  k=log⁡2n⇒T(n)=n T(1)+cnlog⁡2n=cn+cnlog⁡2n=Θ(nlog⁡n)\frac{n}{2^{k}} = 1 \iff k = \log_2 n \quad\Rightarrow\quad T(n) = n\,T(1) + cn\log_2 n = cn + cn\log_2 n = \Theta(n \log n)
For n=8n = 8: 33 levels of merging, 88 work each, 2424 in total, which is 8log⁡288 \log_2 8.

The math

The recursion tree: n work on every level

Cost of each call in the recursion tree

Level 0 costs nn. Level 1 costs n2+n2=n\frac{n}{2} + \frac{n}{2} = n. Level 2 costs 4⋅n4=n4 \cdot \frac{n}{4} = n. The pieces shrink exactly as fast as they multiply.

Add up the levels

T(n)=∑ℓ=0log⁡2n−12ℓ⋅n2ℓ⏟= n per level=nlog⁡2nT(n) = \sum_{\ell=0}^{\log_2 n - 1} \underbrace{2^{\ell} \cdot \frac{n}{2^{\ell}}}_{=\,n \text{ per level}} = n \log_2 n
The same answer as unrolling: log⁡2n\log_2 n levels that each do nn work.
nnnnlog⁡2nn \log_2 nn2n^2
882464
64643844,096
1,0241,02410,2401,048,576
1,000,0001,000,000about 20 million101210^{12}
At a million values merge sort does about 20 million steps; an O(n2)O(n^2) sort does a trillion. See O(n log n) time for the curve.

Complexity

Same time on every input, O(n) space

Input (n)ComparisonsWhy
[38, 27, 43, 3, 9, 82, 10] (7)14runs interleave, every merge goes long
[1, 2, 3, 4, 5, 6, 7] sorted (7)11each merge stops when the left run empties
[1, 2, 4, 3, 5, 6, 7] nearly sorted (7)11one swapped pair barely changes anything
[7, 6, 5, 4, 3, 2, 1] reversed (7)9the right run empties first, after few comparisons
[4, 2, 7, 1] small (4)51 + 1 + 3
The counts wobble, but the split tree and the log⁡2n\log_2 n levels never change. Best, average and worst are all Θ(nlog⁡n)\Theta(n \log n).

Comparisons in one merge

min⁡(p,q)  ≤  Cmerge(p,q)  ≤  p+q−1\min(p, q) \;\le\; C_{\text{merge}}(p, q) \;\le\; p + q - 1
The low end happens when one run is entirely smaller than the other, as in sorted or reversed input. Writes are always exactly p+qp + q.

Head to head

Merge vs quick vs heap sort

PropertyMerge sortQuick sortHeap sort
Best timeO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)
Average timeO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)
Worst timeO(nlog⁡n)O(n \log n)O(n2)O(n^2)O(nlog⁡n)O(n \log n)
Extra spaceO(n)O(n)O(log⁡n)O(\log n) stackO(1)O(1)
StableYesNoNo
In placeNoYesYes
Best useStability, linked lists, disk dataFast general array sortingGuaranteed time with no extra memory
Merge sort is the only one of the three that is both stable and guaranteed O(nlog⁡n)O(n \log n).

Which O(n log n) sort?

In everyday code, use the language's built-in sort; in Python and Java (for objects) that is Timsort, a merge sort descendant.

Why you cannot beat n log n by comparing

log⁡2(n!)≈nlog⁡2n−1.44 n\log_2(n!) \approx n \log_2 n - 1.44\,n
Any comparison sort must tell apart all n!n! orders, which needs at least log⁡2(n!)\log_2(n!) yes or no answers. Merge sort's worst case is within a small constant of this, so it is asymptotically optimal.

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 O(nlog⁡n)O(n \log n), no call stack.

  • Linked lists

    Merging lists is just relinking nodes, so the extra O(n)O(n) 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.

Python
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]
Bottom-up merge sort: double the run width each pass.
Edit and run it in your browser

External merge sort

Databases and the Unix 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 O(nlog⁡n)O(n \log n) 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 O(n)O(n) 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: O(nlog⁡n)O(n \log n).

  • Merge k sorted lists

    The merge step with a heap: always take the smallest front among kk runs, O(Nlog⁡k)O(N \log k).

  • 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 pp and qq costs at most p+q−1p + q - 1 comparisons and p+qp + q writes.
  • T(n)=2T(n/2)+nT(n) = 2T(n/2) + n unrolls to log⁡2n\log_2 n levels of nn work: Θ(nlog⁡n)\Theta(n \log n) in the best, average and worst case.
  • O(n)O(n) extra space for the merge buffers plus O(log⁡n)O(\log n) 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.

Sources