Skip to the content.

21. Merge Sort

Back to the index

Split the array in half, sort each half recursively, then merge the two sorted halves. Always O(n log n) and stable, at the cost of O(n) extra memory.

How it works

Merge sort is the textbook divide and conquer algorithm. Splitting stops at arrays of length 1, which are trivially sorted. The real work is merge: two pointers walk the sorted halves and repeatedly copy the smaller front item. There are about log n levels of splitting and each level does O(n) merging work.

The diagram shows the split tree; the trace shows every merge in the order the recursion performs them.

Diagram

graph TD
    m["5 2 9 1 6 3"]
    ml["5 2 9"]
    mll["5"]
    ml --> mll
    mlr["2 9"]
    mlrl["2"]
    mlr --> mlrl
    mlrr["9"]
    mlr --> mlrr
    ml --> mlr
    m --> ml
    mr["1 6 3"]
    mrl["1"]
    mr --> mrl
    mrr["6 3"]
    mrrl["6"]
    mrr --> mrrl
    mrrr["3"]
    mrr --> mrrr
    mr --> mrr
    m --> mr

Step-by-step trace

Input: Sort [5, 2, 9, 1, 6, 3].

Step Depth Merge left Merge right Result
1 2 [2] [9] [2, 9]
2 1 [5] [2, 9] [2, 5, 9]
3 2 [6] [3] [3, 6]
4 1 [1] [3, 6] [1, 3, 6]
5 0 [2, 5, 9] [1, 3, 6] [1, 2, 3, 5, 6, 9]

Result: Sorted: [1, 2, 3, 5, 6, 9].

Complexity

Operation Time Space
All cases O(n log n) O(n)
Stable? yes (take from the left half on ties) -

Python reference implementation

def merge_sort(a):
    if len(a) <= 1:
        return list(a)
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    return merge(left, right)


def merge(left, right):
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:        # <= keeps the sort stable
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Insertion Sort Next: Quick Sort