TExcelTAD

Merge Sort

Merge sort is a divide and conquer algorithm with a guaranteed O(n log n) running time. It rests on one simple observation: merging two sorted lists into one sorted list is easy. You only ever need to compare the two front values and take the smaller one.

So merge sort:

  1. Divides the array into two halves.
  2. Sorts each half recursively (a half with one value is already sorted).
  3. Merges the two sorted halves.

Merging two sorted lists

python · try it yourself
def 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: stable
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])            # one of these is empty
    result.extend(right[j:])
    return result

print(merge([8, 17, 41], [5, 12, 26, 33]))
[5, 8, 12, 17, 26, 33, 41]

Each comparison places one value, so merging lists with n values in total takes at most n - 1 comparisons.

The whole algorithm

Watch the array get split down to single values and then merged back up. The highlighted range shows which two sorted runs are being merged.

The implementation below splits the same way (the left half gets the middle value) and prints every merge in the same order as the animation:

python · try it yourself
def merge(left, right):
    result, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i]); i += 1
        else:
            result.append(right[j]); j += 1
    return result + left[i:] + right[j:]

def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = (len(arr) - 1) // 2 + 1         # left half takes the middle value
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    merged = merge(left, right)
    print(f"merge {left} and {right} -> {merged}")
    return merged

print(merge_sort([41, 17, 8, 26, 33, 5, 12]))
merge [41] and [17] -> [17, 41]
merge [8] and [26] -> [8, 26]
merge [17, 41] and [8, 26] -> [8, 17, 26, 41]
merge [33] and [5] -> [5, 33]
merge [5, 33] and [12] -> [5, 12, 33]
merge [8, 17, 26, 41] and [5, 12, 33] -> [5, 8, 12, 17, 26, 33, 41]
[5, 8, 12, 17, 26, 33, 41]

Why O(n log n)?

Halving n values repeatedly reaches single values after about log₂ n levels. At every level, all the merges together touch each value once, which is O(n) work. So the total is O(n log n), and this holds for every input; merge sort has no bad case. Let's count the comparisons:

python · try it yourself
import math

def merge_sort_count(arr, counter):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort_count(arr[:mid], counter)
    right = merge_sort_count(arr[mid:], counter)
    result, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        counter[0] += 1
        if left[i] <= right[j]:
            result.append(left[i]); i += 1
        else:
            result.append(right[j]); j += 1
    return result + left[i:] + right[j:]

for n in [8, 64, 1024]:
    for name, data in [("sorted", list(range(n))), ("reversed", list(range(n, 0, -1)))]:
        counter = [0]
        merge_sort_count(data, counter)
        print(f"n={n:>4} {name:>8}: {counter[0]:>5} comparisons  (n·log2 n = {int(n * math.log2(n))})")
n=   8   sorted:    12 comparisons  (n·log2 n = 24)
n=   8 reversed:    12 comparisons  (n·log2 n = 24)
n=  64   sorted:   192 comparisons  (n·log2 n = 384)
n=  64 reversed:   192 comparisons  (n·log2 n = 384)
n=1024   sorted:  5120 comparisons  (n·log2 n = 10240)
n=1024 reversed:  5120 comparisons  (n·log2 n = 10240)

Sorted and reversed input cost about half of n log₂ n (one side runs out early in every merge), and no input costs more than n log₂ n.

Bottom-up merge sort

Recursion is not required. The bottom-up version merges runs of width 1 into runs of width 2, then 4, then 8, until one run covers the whole array:

python · try it yourself
def merge_sort_bottom_up(arr):
    width = 1
    while width < len(arr):
        merged = []
        for start in range(0, len(arr), 2 * width):
            left = arr[start:start + width]
            right = arr[start + width:start + 2 * width]
            i = j = 0
            while i < len(left) and j < len(right):
                if left[i] <= right[j]:
                    merged.append(left[i]); i += 1
                else:
                    merged.append(right[j]); j += 1
            merged += left[i:] + right[j:]
        arr = merged
        print(f"width {width}: {arr}")
        width *= 2
    return arr

merge_sort_bottom_up([41, 17, 8, 26, 33, 5, 12])
width 1: [17, 41, 8, 26, 5, 33, 12]
width 2: [8, 17, 26, 41, 5, 12, 33]
width 4: [5, 8, 12, 17, 26, 33, 41]

Properties

Property Merge sort
Time (best, average, worst) O(n log n)
Extra memory O(n) for the merged lists
Stable? Yes (take from the left run on ties)
Good for linked lists, huge files on disk (external sorting), when a worst-case guarantee matters

Note: Python's built-in sort, Timsort, is a merge sort that detects already-sorted runs in the data and uses insertion sort for short pieces. That's why sorted() is so fast on real-world, partly ordered data.

Test yourself

What is the key operation that merge sort repeats?

  1. Swapping neighbours
  2. Partitioning around a pivot
  3. Merging two sorted lists into one
  4. Counting occurrences

What is merge sort's worst-case time complexity?

  1. O(n)
  2. O(n log n)
  3. O(n²)
  4. O(log n)

What is the main disadvantage of merge sort compared with quick sort?

  1. It is unstable
  2. It needs O(n) extra memory
  3. It has an O(n²) worst case
  4. It only works on integers