Intermediate 8 min

Merge sort

Merge sort splits a list into smaller parts, sorts each part, and merges the sorted parts.

How it works

Put one marker at the start of each sorted half. Only their current values can be the next smallest. Advance the chosen marker and leave the other where it is. Each merging level processes the full input, and repeatedly halving creates about log₂ n levels, giving O(n log n) time.

Walk through an example

To merge [2, 7] and [3, 5], compare the first unused items. Take 2, then 3, then 5. Append the unconsumed 7. The merge examines each item once.

What to watch for

Split down to lists of length 0 or 1. Picking the left item on a tie preserves the original order of equal keys.

Code example

def merge(left, right):
    out = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

Check your understanding

What two sorted halves are merged in the final step?

See the example and explanation
Worked example
Given [6, 1, 4, 3]
Answer [1, 6] and [3, 4]

The original halves [6, 1] and [4, 3] sort independently. Their final merge gives [1, 3, 4, 6].

Open practice problem
Next lessonQuicksort and partitioning