Kodewick
Start learning →
Merge sort43 / 52

Merge sort

Lesson 43 of 52 · Part 8 · Sorting · about 24 minutes

Merge sort cuts the list in half, sorts each half recursively and merges the two sorted halves in one walk from front to back; it takes about n log₂ n comparisons on any input, and merging with <= keeps it stable.

Last lesson's insertion sort needs about 50 million comparisons for 10,000 reversed numbers. Merge sort needs only about n log₂ n comparisons whatever the input: under 140,000 for 10,000 numbers, more than three hundred times fewer. Its idea fits in one sentence: merging two lists that are already sorted takes one walk from front to back. So a big list is cut in half, each half is sorted (recursively), and the two are merged. The Timsort behind Python's sorted is built on merge sort; databases sorting tables too big for memory (external sorting) also sort chunks first and then merge them.

Merging two sorted lists

Both lists are already sorted. Keep a pointer at the front of each; each time compare the two numbers they point at, put the smaller into the result, and move that pointer one on. When one side runs out, everything left on the other side is larger than what's in the result, so just append it.

left, right and outleftrightout14723901234567891011↑i↑j↑k

Merging 1 4 7 and 2 3 9: compare the fronts of the two sides and put the smaller into out; when the left runs out, the 9 left on the right is appended. 5 comparisons

The two sides hold n numbers in all, and each comparison places one, so at most n − 1 comparisons: merging is O(n).

Choose one

Merging 1 4 7 and 2 3 9: which side does each of the 6 numbers put into out come from, in order? (L = left half, R = right half)

Choose one

How many comparisons does it take to merge 2 5 8 and 1 3 9 10?

<= keeps it stable

Stable means equal items keep their original order after sorting. Sort a class list by score and students with the same score stay in their original order: that is a stable sort at work. Whether merge sort is stable comes down to one comparison in the merge.

The comparison is left[i] <= right[j], not <: on a tie, the left one goes first. The left one was earlier to begin with, so equal items keep their original order and merge sort is stable. With < the numbers still come out right, but equal items swap their order:

main.py
1def merge(left, right, key, strict):2    out = []3    i = j = 04    while i < len(left) and j < len(right):5        if strict:6            take_left = key(left[i]) < key(right[j])7        else:8            take_left = key(left[i]) <= key(right[j])9        if take_left:10            out.append(left[i])11            i += 112        else:13            out.append(right[j])14            j += 115    out.extend(left[i:])16    out.extend(right[j:])17    return out18 19print(merge([1, 4, 7], [2, 3, 9], lambda x: x, False))20 21left = [(85, "Li"), (90, "Wang")]           # the half that was in front22right = [(90, "Zhang"), (95, "Chen")]23score = lambda r: r[0]24print("<=:", merge(left, right, score, False))25print("< :", merge(left, right, score, True))
Output
[1, 2, 3, 4, 7, 9]
<=: [(85, 'Li'), (90, 'Wang'), (90, 'Zhang'), (95, 'Chen')]
< : [(85, 'Li'), (90, 'Zhang'), (90, 'Wang'), (95, 'Chen')]
Change it

Each person is (score, name), sorted by score from low to high. Change only the comparison in the green box so people with the same score keep their original order (A before C, B before D).

1def merge(left, right):2    out = []3    i = j = 04    while i < len(left) and j < len(right):5        if left[i][0]  right[j][0]:6            out.append(left[i])7            i += 18        else:9            out.append(right[j])10            j += 111    out.extend(left[i:])12    out.extend(right[j:])13    return out14 15def merge_sort(a):16    if len(a) <= 1:17        return a18    mid = len(a) // 219    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))20 21people = [(2, "A"), (1, "B"), (2, "C"), (1, "D")]22print(" ".join(str(s) + n for s, n in merge_sort(people)))
Should print
1B 1D 2A 2C
Exercise 1

Merge two sorted lists

Complete merge(left, right): both are sorted, smallest first; return a new merged list. On a tie the item from left goes first, so it is stable (compare records by their first item).

It should print
[(1, 'a'), (2, 'c'), (4, 'b'), (4, 'd'), (5, 'e')]
[(3, 'x')]
[(2, 'p'), (2, 'q'), (2, 'r')]
exercise1.py
1def merge(left, right):2    out = []3    i = j = 04    # while neither side is used up, compare left[i][0] and right[j][0]; append what is left at the end5    return out6 7print(merge([(1, "a"), (4, "b")], [(2, "c"), (4, "d"), (5, "e")]))8print(merge([], [(3, "x")]))9print(merge([(2, "p"), (2, "q")], [(2, "r")]))
Output
Press Run or Ctrl+Enter

The slicing version: easiest to read

With merge, merge sort itself is three lines: 0 or 1 items are already sorted; otherwise cut in half, sort each half, merge. In the figure, the arrows down are calls, and the dashed arrows up are returns.

5 2 4 7 1 3 2 6
1def merge_sort(a):2    global made3    if len(a) <= 1:4        return a5    mid = len(a) // 26    made += 2                                # a[:mid] and a[mid:] are each a new list7    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))

Sorting 5 2 4 7 1 3 2 6: cut level by level into single items, then merged back level by level. Under each node is the sorted list it returns
main.py
1made = 0                 # how many new lists were made2cmps = 03 4def merge(left, right):5    global made, cmps6    out = []7    made += 18    i = j = 09    while i < len(left) and j < len(right):10        cmps += 111        if left[i] <= right[j]:12            out.append(left[i])13            i += 114        else:15            out.append(right[j])16            j += 117    out.extend(left[i:])18    out.extend(right[j:])19    return out20 21def merge_sort(a):22    global made23    if len(a) <= 1:24        return a25    mid = len(a) // 226    made += 2                                # a[:mid] and a[mid:] are each a new list27    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))28 29print(merge_sort([5, 2, 4, 7, 1, 3, 2, 6]), cmps)30 31made = cmps = 032data = [(i * 7919) % 10007 for i in range(1024)]33result = merge_sort(data)34print(result == sorted(data), "comparisons", cmps, "new lists", made)
Output
[1, 2, 2, 3, 4, 5, 6, 7] 17
True comparisons 9022 new lists 3069

The slicing version reads well, but it keeps making new lists: each cut makes two, each merge one more (the left[i:] inside extend is new too, and isn't counted). 1024 numbers make over three thousand lists, and every item is copied around at every level. It also returns a new list; the original data is not sorted.

Choose one

merge_sort gets 7 numbers, [5, 2, 4, 7, 1, 3, 6]. Which two parts does the first split make?

Put in orderDrag, or use the arrows

Put the 4 lines of the slicing merge_sort in order so the program sorts 5 2 4 7 1 3 2 6.

  1. right = merge_sort(a[mid:])
  2. left = merge_sort(a[:mid])
  3. return merge(left, right)
  4. mid = len(a) // 2
Should print
[1, 2, 2, 3, 4, 5, 6, 7]

The index version: one buffer

Instead of slicing, use indexes lo, hi for "sorting the stretch a[lo:hi]". Merging needs somewhere to put the result, so make one list buf as long as a at the start; each merge borrows its [lo, hi) stretch, then copies back into a. The whole sort makes only this one list, and sorts a in place.

main.py
1def merge_sort(a):2    buf = [0] * len(a)                 # the only extra list3    cmps = 04 5    def sort(lo, hi):                  # sort a[lo:hi]6        nonlocal cmps7        if hi - lo <= 1:8            return9        mid = (lo + hi) // 210        sort(lo, mid)11        sort(mid, hi)12        i, j, k = lo, mid, lo13        while i < mid and j < hi:14            cmps += 115            if a[i] <= a[j]:16                buf[k] = a[i]17                i += 118            else:19                buf[k] = a[j]20                j += 121            k += 122        while i < mid:                 # what's left on the left23            buf[k] = a[i]24            i += 125            k += 126        while j < hi:                  # what's left on the right27            buf[k] = a[j]28            j += 129            k += 130        for t in range(lo, hi):        # copy back into a31            a[t] = buf[t]32 33    sort(0, len(a))34    return cmps35 36a = [5, 2, 4, 7, 1, 3, 2, 6]37print(merge_sort(a), a)38 39data = [(i * 7919) % 10007 for i in range(1024)]40expect = sorted(data)41print(merge_sort(data), data == expect)
Output
17 [1, 2, 2, 3, 4, 5, 6, 7]
9022 True

The comparisons are exactly the slicing version's (17), just without lists made everywhere. The extra space is this one buf, O(n): merge sort in place without extra space is very hard, and this is its price. Merge sorts in C and Java libraries are written this way.

Slicing versionIndex version
Codethree lines, easiest to readlonger, with lo, hi and mid to manage
New liststwo or three per call, over three thousand for n = 1024one buf
Extra spaceO(n) at any moment, but always allocating and freeingO(n), allocated once
Resultreturns a new list, the original untouchedsorts a in place
Fill inTap one to fill a blank; tap a blank to take it back

In the index version a part is a[lo:hi] (hi not included). At which index does the right half start? Fill in the blank so it sorts correctly.

1def merge_sort(a):2    buf = [0] * len(a)3 4    def sort(lo, hi):                  # a[lo:hi]5        if hi - lo <= 1:6            return7        mid = (lo + hi) // 28        sort(lo, mid)9        sort(mid, hi)10        i, j, k = lo, , lo11        while i < mid and j < hi:12            if a[i] <= a[j]:13                buf[k] = a[i]14                i += 115            else:16                buf[k] = a[j]17                j += 118            k += 119        while i < mid:20            buf[k] = a[i]21            i += 122            k += 123        while j < hi:24            buf[k] = a[j]25            j += 126            k += 127        for t in range(lo, hi):28            a[t] = buf[t]29 30    sort(0, len(a))31 32a = [5, 2, 4, 7, 1, 3, 2, 6]33merge_sort(a)34print(a)

Why n log n: counting it

Look at the recursion tree: each level down halves the stretches, so there are log₂ n levels (3 for 8 numbers, 10 for 1024). All the merges on one level together place each of the n numbers once, with fewer than n comparisons. So fewer than n log₂ n comparisons in all: O(n log n).

The recursion depth is log₂ n + 1 too: only 11 levels for 1024 numbers, 21 for a million, nowhere near Python's recursion limit (1000 by default).

main.py
1def merge_sort(a):2    buf = [0] * len(a)3    cmps = 04 5    def sort(lo, hi):6        nonlocal cmps7        if hi - lo <= 1:8            return9        mid = (lo + hi) // 210        sort(lo, mid)11        sort(mid, hi)12        i, j, k = lo, mid, lo13        while i < mid and j < hi:14            cmps += 115            if a[i] <= a[j]:16                buf[k] = a[i]17                i += 118            else:19                buf[k] = a[j]20                j += 121            k += 122        buf[k:hi] = a[i:mid] if i < mid else a[j:hi]23        a[lo:hi] = buf[lo:hi]24 25    sort(0, len(a))26    return cmps27 28n = 102429print("n log2 n =", n * 10, " n(n-1)/2 =", n * (n - 1) // 2)30for name, data in [("sorted", list(range(n))), ("reversed", list(range(n, 0, -1))), ("mixed", [(i * 7919) % 10007 for i in range(n)])]:31    print(name, merge_sort(data))
Output
n log2 n = 10240  n(n-1)/2 = 523776
sorted 5120
reversed 5120
mixed 9022

(Here the leftover stretch is copied over in one slice, saving two while loops; only comparisons are counted.)

Sorted and reversed both take 5120: in every merge one side runs out first, after only half the comparisons; mixed takes 9022, still under n log₂ n = 10,240. Bubble and insertion sort need 520,000 on reversed input. Merge sort is O(n log n) best, worst and on average: there is no bad input.

Exams love bottom-up two-way merge sort: no recursion, just merge in twos, then in fours, with the sorted runs doubling in length on every pass. When n is a power of 2 it merges exactly the same runs as the recursive version.

a5173826401234567

Bottom-up two-way merge sort on 5 1 7 3 8 2 6 4: each pass merges neighbouring runs, and the sorted runs double in length

In exams: two-way merge sort takes ⌈log₂ n⌉ passes; after pass k, every run of 2ᵏ is sorted.

Guess the outputA wrong guess is fine

Two merges: how many comparisons does each make?

1def merge(left, right):2    out, i, j, cmps = [], 0, 0, 03    while i < len(left) and j < len(right):4        cmps += 15        if left[i] <= right[j]:6            out.append(left[i])7            i += 18        else:9            out.append(right[j])10            j += 111    out.extend(left[i:])12    out.extend(right[j:])13    return cmps14 15print(merge([1, 2, 3], [4, 5, 6]), merge([1, 4, 5], [2, 3, 6]))
Choose one

Two-way merge sort on 6 2 8 4 1 7 3 5: pass 1 merges in twos, pass 2 in fours. What does the array look like after pass 2?

Choose one

You give merge sort an array that is already sorted. How long does it take?

In interviews: merge sort questions test three points: stable (<= when merging), always O(n log n), O(n) extra space. Two classic problems use its merge: sorting a linked list (find the middle with fast and slow pointers, cut, and merge by changing only next, no extra space; LeetCode 148) and counting inversions (when an item from the right goes first, everything left on the left side is larger than it).

Exercise 2

Count the inversions

An inversion is a pair with i < j and a[i] > a[j]. Complete sort_count(a): use merge sort to return (the sorted list, the number of inversions) in O(n log n), without two nested loops.

It should print
([1, 2, 3, 4, 5], 3)
([1, 2, 3, 4, 5], 10)
([1, 2, 3], 0)
([1, 3, 3], 2)
exercise2.py
1def sort_count(a):2    if len(a) <= 1:3        return a, 04    mid = len(a) // 25    left, x = sort_count(a[:mid])6    right, y = sort_count(a[mid:])7    out = []8    count = x + y9    i = j = 010    # merge: when an item from the right goes first, the len(left) - i items left on the left are all larger11    return out, count12 13print(sort_count([2, 4, 1, 3, 5]))14print(sort_count([5, 4, 3, 2, 1]))15print(sort_count([1, 2, 3]))16print(sort_count([3, 3, 1]))
Output
Press Run or Ctrl+Enter

How you write it at work

Sort with sorted: Timsort is an improved merge sort, stable and O(n log n), and it also takes advantage of stretches that are already sorted.

To merge two sorted lists, the easiest is sorted(a + b): Timsort sees two sorted stretches and merges them directly, close to O(n). To merge many sorted lists (say, files each sorted on their own) without reading everything into memory, the standard library has heapq.merge(*lists): it yields the smallest as it reads, using a heap of size k. The idea, written out by hand:

main.py
1import heapq2 3def merge_k(lists):4    h = []5    for idx, lst in enumerate(lists):6        if lst:7            heapq.heappush(h, (lst[0], idx, 0))     # (value, which list, index)8    out = []9    while h:10        val, idx, pos = heapq.heappop(h)11        out.append(val)12        if pos + 1 < len(lists[idx]):13            heapq.heappush(h, (lists[idx][pos + 1], idx, pos + 1))14    return out15 16a, b = [1, 4, 7], [2, 3, 9]17print(sorted(a + b))18print(merge_k([[1, 4, 7], [2, 3, 9], [0, 8], []]))
Output
[1, 2, 3, 4, 7, 9]
[0, 1, 2, 3, 4, 7, 8, 9]

The heap holds (value, which list, index): on equal values the second item decides, so nothing after it is ever compared, and the result is stable. k lists with n numbers in all is O(n log k).

  • Sorting: sorted / list.sort.
  • Two sorted lists: sorted(a + b).
  • Many sorted lists, or files and streams: heapq.merge, needing memory for only k items.
  • Sorting a linked list: use merge sort (find the middle with fast and slow pointers); don't copy into a list and sort, as the interviewer wants to see the merge.
Choose one

k sorted lists, n numbers in all, merged with heapq.merge (at most k items in the heap). How long does it take?

Summary

Take-away

Merge sort

  • Merging two sorted lists: compare the two fronts, the smaller goes first, O(n); <= keeps it stable
  • Cut, sort each half, merge: log n levels, under n comparisons each, always O(n log n)
  • The slicing version reads best but makes new lists everywhere; the index version uses one buf, O(n) extra
  • The recursion is only log n deep, so the recursion limit is no worry
  • At work: sorted is an improved merge sort; many sorted lists go through heapq.merge
1def merge_sort(a):2    if len(a) <= 1:3        return a4    mid = len(a) // 25    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))