ZetCode

Python merge sort

last modified November 18, 2026 Python 3.15

In this article we explain the merge sort algorithm in Python. We implement recursive and iterative versions, use merge sort to count inversions, merge sorted streams with heapq.merge, and sort a file that is processed in chunks.

Merge sort is a divide and conquer algorithm. It has a guaranteed O(n log n) running time and is stable. Python's own list.sort and sorted are based on merging too: they find sorted runs in the data and merge them.

Merge sort algorithm

Merge sort splits the list into two halves, sorts each half recursively, and merges the two sorted halves into one sorted list. A list of zero or one element is already sorted, which ends the recursion. The real work is done by the merge step: it repeatedly takes the smaller of the two front elements of the halves.

PropertyValue
Time (best, average, worst)O(n log n)
Extra spaceO(n) for merging
Stableyes
Access patternsequential, suitable for linked lists and files

Merge sort example

The following is a top-down merge sort that returns a new list.

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


def merge_sort(vals):
    if len(vals) <= 1:
        return vals
    mid = len(vals) // 2
    return merge(merge_sort(vals[:mid]), merge_sort(vals[mid:]))


nums = [38, 27, 43, 3, 9, 82, 10]
print(merge_sort(nums))
print(nums)

The merge function walks both lists with two indexes and appends the smaller front element. When one list is exhausted, the rest of the other one is appended unchanged. The <= comparison takes the left element on ties, which makes the sort stable. The merge_sort function slices the list in halves; slices are copies, so the original list is not modified, as the second line of the output shows.

$ python merge_sort.py
[3, 9, 10, 27, 38, 43, 82]
[38, 27, 43, 3, 9, 82, 10]

Tracing the recursion

We print every split and merge, indented by the recursion depth.

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


def merge_sort(vals, depth=0):
    indent = '  ' * depth
    if len(vals) <= 1:
        return vals
    mid = len(vals) // 2
    print(f'{indent}split {vals[:mid]} {vals[mid:]}')
    left = merge_sort(vals[:mid], depth + 1)
    right = merge_sort(vals[mid:], depth + 1)
    res = merge(left, right)
    print(f'{indent}merge {left} {right} -> {res}')
    return res


merge_sort([38, 27, 43, 3, 9, 82, 10])

The list is split until the pieces have a single element. The merges then happen from the bottom up. A list of n elements has about log2n levels, and each level merges n elements in total, which gives the O(n log n) running time.

$ python merge_trace.py
split [38, 27, 43] [3, 9, 82, 10]
  split [38] [27, 43]
    split [27] [43]
    merge [27] [43] -> [27, 43]
  merge [38] [27, 43] -> [27, 38, 43]
  split [3, 9] [82, 10]
    split [3] [9]
    merge [3] [9] -> [3, 9]
    split [82] [10]
    merge [82] [10] -> [10, 82]
  merge [3, 9] [10, 82] -> [3, 9, 10, 82]
merge [27, 38, 43] [3, 9, 10, 82] -> [3, 9, 10, 27, 38, 43, 82]

Sorting in place with one buffer

The first version creates many small lists. A more economical version sorts the list in place and uses a single auxiliary buffer for all merges.

merge_inplace.py
def merge_sort(vals):
    buf = vals.copy()

    def sort(lo, hi):
        if hi - lo <= 1:
            return
        mid = (lo + hi) // 2
        sort(lo, mid)
        sort(mid, hi)
        if vals[mid - 1] <= vals[mid]:
            return
        buf[lo:hi] = vals[lo:hi]
        i, j = lo, mid
        for k in range(lo, hi):
            if j >= hi or (i < mid and buf[i] <= buf[j]):
                vals[k] = buf[i]
                i += 1
            else:
                vals[k] = buf[j]
                j += 1

    sort(0, len(vals))


nums = [5, 2, 9, 1, 5, 6, 3, 8, 7, 4]
merge_sort(nums)
print(nums)

words = ['pear', 'fig', 'apple', 'kiwi', 'banana']
merge_sort(words)
print(words)

The inner sort function works on the index range [lo, hi), so no slices of the input are created during the recursion. Before merging, the range is copied to buf and merged back into vals. If the last element of the left half is not greater than the first element of the right half, the range is already sorted and the merge is skipped; this makes sorted input much faster.

$ python merge_inplace.py
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
['apple', 'banana', 'fig', 'kiwi', 'pear']

Bottom-up merge sort

Merge sort does not need recursion. The bottom-up variant treats every element as a sorted run of width one, merges neighbouring runs into runs of width two, then four, and so on.

bottom_up.py
def merge_sort(vals):
    n = len(vals)
    width = 1
    while width < n:
        res = []
        for lo in range(0, n, 2 * width):
            left = vals[lo:lo + width]
            right = vals[lo + width:lo + 2 * width]
            i = j = 0
            while i < len(left) and j < len(right):
                if left[i] <= right[j]:
                    res.append(left[i])
                    i += 1
                else:
                    res.append(right[j])
                    j += 1
            res += left[i:] + right[j:]
        vals = res
        print(f'width {width}: {vals}')
        width *= 2
    return vals


merge_sort([6, 5, 3, 1, 8, 7, 2, 4, 0])

Each pass of the while loop merges pairs of runs of the current width. The last run may be shorter or have no partner; in that case it is copied unchanged. The output shows the runs doubling in each pass. With nine elements, the 0 waits alone until the last pass.

$ python bottom_up.py
width 1: [5, 6, 1, 3, 7, 8, 2, 4, 0]
width 2: [1, 3, 5, 6, 2, 4, 7, 8, 0]
width 4: [1, 2, 3, 4, 5, 6, 7, 8, 0]
width 8: [0, 1, 2, 3, 4, 5, 6, 7, 8]

Stability

Stability allows sorting by several keys in multiple passes: first by the secondary key, then by the primary key.

merge_stable.py
from operator import attrgetter
from typing import NamedTuple


class Order(NamedTuple):
    id: int
    customer: str
    total: float


def merge_sort(vals, key):
    if len(vals) <= 1:
        return vals
    mid = len(vals) // 2
    left = merge_sort(vals[:mid], key)
    right = merge_sort(vals[mid:], key)
    res = []
    i = j = 0
    while i < len(left) and j < len(right):
        if key(right[j]) < key(left[i]):
            res.append(right[j])
            j += 1
        else:
            res.append(left[i])
            i += 1
    return res + left[i:] + right[j:]


orders = [
    Order(1, 'Smith', 120.0), Order(2, 'Brown', 45.5),
    Order(3, 'Smith', 30.0), Order(4, 'Adams', 99.9),
    Order(5, 'Brown', 210.0), Order(6, 'Adams', 15.0),
]

by_total = merge_sort(orders, key=attrgetter('total'))
by_customer = merge_sort(by_total, key=attrgetter('customer'))

for order in by_customer:
    print(order)

The merge takes the right element only when its key is strictly smaller. We sort the orders by total first and then by customer. Orders of the same customer keep the order of the first pass, so they appear sorted by total. The same technique works with sorted.

$ python merge_stable.py
Order(id=6, customer='Adams', total=15.0)
Order(id=4, customer='Adams', total=99.9)
Order(id=2, customer='Brown', total=45.5)
Order(id=5, customer='Brown', total=210.0)
Order(id=3, customer='Smith', total=30.0)
Order(id=1, customer='Smith', total=120.0)

Counting inversions

An inversion is a pair of elements in the wrong order. Counting the pairs directly takes O(n2) time; a modified merge sort counts them in O(n log n).

inversions.py
def count_inversions(vals):
    if len(vals) <= 1:
        return vals, 0
    mid = len(vals) // 2
    left, a = count_inversions(vals[:mid])
    right, b = count_inversions(vals[mid:])
    res = []
    count = a + b
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            res.append(left[i])
            i += 1
        else:
            res.append(right[j])
            count += len(left) - i
            j += 1
    return res + left[i:] + right[j:], count


ranking_a = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']
ranking_b = ['Bob', 'Alice', 'Eve', 'Carol', 'Dave']

positions = [ranking_a.index(name) for name in ranking_b]
_, inv = count_inversions(positions)
print(positions, 'inversions:', inv)

print(count_inversions([5, 4, 3, 2, 1])[1])
print(count_inversions(list(range(1000, 0, -1)))[1])

When the merge takes an element from the right half, that element is smaller than all the remaining elements of the left half. All of them form an inversion with it, so we add len(left) - i. The number of inversions measures how different two rankings are; here, the positions of the names of the second ranking in the first one contain three inversions. A reversed list of n elements has n(n - 1)/2 inversions.

$ python inversions.py
[1, 0, 4, 2, 3] inversions: 3
10
499500

Merging with heapq.merge

The standard library has a merge function. The heapq.merge function merges any number of sorted iterables into a single sorted iterator.

heapq_merge.py
import heapq

morning = [3, 8, 15, 21]
noon = [1, 9, 10, 30]
evening = [2, 4, 22]

print(list(heapq.merge(morning, noon, evening)))

logs_a = [('08:01', 'a: start'), ('08:05', 'a: load'), ('08:30', 'a: stop')]
logs_b = [('08:02', 'b: start'), ('08:05', 'b: load'), ('08:10', 'b: stop')]

for time, msg in heapq.merge(logs_a, logs_b, key=lambda e: e[0]):
    print(time, msg)

print(list(heapq.merge([9, 5, 1], [8, 2], reverse=True)))

The function is lazy: it reads only one element from each input at a time. It accepts the key and reverse parameters; with reverse=True, the inputs must be sorted in descending order. On equal keys, the element from the earlier iterable comes first, as with the two 08:05 log entries.

$ python heapq_merge.py
[1, 2, 3, 4, 8, 9, 10, 15, 21, 22, 30]
08:01 a: start
08:02 b: start
08:05 a: load
08:05 b: load
08:10 b: stop
08:30 a: stop
[9, 8, 5, 2, 1]

External sorting

When the data does not fit into memory, we can use external sorting. The data is read in chunks, each chunk is sorted in memory and written to a temporary file, and the sorted files are then merged.

external_sort.py
import heapq
import random
import tempfile
from pathlib import Path


def external_sort(src, dest, chunk_size):
    runs = []
    with open(src) as f:
        while True:
            chunk = [int(line) for _, line in zip(range(chunk_size), f)]
            if not chunk:
                break
            chunk.sort()
            run = tempfile.NamedTemporaryFile('w+', delete=False)
            run.writelines(f'{n}\n' for n in chunk)
            run.seek(0)
            runs.append(run)

    print(f'{len(runs)} sorted runs of up to {chunk_size} numbers')
    streams = [(int(line) for line in run) for run in runs]
    with open(dest, 'w') as out:
        out.writelines(f'{n}\n' for n in heapq.merge(*streams))

    for run in runs:
        run.close()
        Path(run.name).unlink()


rng = random.Random(8)
Path('numbers.txt').write_text(
    ''.join(f'{rng.randint(0, 1_000_000)}\n' for _ in range(100_000)))

external_sort('numbers.txt', 'sorted.txt', chunk_size=10_000)

nums = [int(line) for line in Path('sorted.txt').read_text().split()]
print(len(nums), nums[:5], nums[-3:])
print(nums == sorted(nums))

We generate a file with 100,000 random numbers and sort it in chunks of 10,000. The zip with a range reads at most chunk_size lines from the file. Each sorted chunk is written to a temporary file. Generator expressions turn the temporary files back into streams of integers, and heapq.merge merges them while holding only one number per run in memory.

$ python external_sort.py
10 sorted runs of up to 10000 numbers
100000 [6, 8, 20, 33, 37] [999966, 999973, 999974]
True

Benchmark

We compare our merge sort with the built-in sorted.

benchmark.py
import random
import timeit


def merge_sort(vals):
    if len(vals) <= 1:
        return vals
    mid = len(vals) // 2
    left = merge_sort(vals[:mid])
    right = merge_sort(vals[mid:])
    res = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            res.append(left[i])
            i += 1
        else:
            res.append(right[j])
            j += 1
    res.extend(left[i:])
    res.extend(right[j:])
    return res


rng = random.Random(9)

for n in (10_000, 100_000):
    data = [rng.randint(0, 1_000_000) for _ in range(n)]
    t_merge = timeit.timeit(lambda: merge_sort(data), number=3) / 3
    t_sorted = timeit.timeit(lambda: sorted(data), number=3) / 3
    print(f'n={n:>7}  merge sort {t_merge:.5f} s  sorted {t_sorted:.5f} s')

Both algorithms are O(n log n), so the ratio between them stays about the same when the input grows. The built-in function is roughly ten times faster, because it runs in C and exploits existing order in the data. The times vary between runs and machines.

$ python benchmark.py
n=  10000  merge sort 0.01179 s  sorted 0.00106 s
n= 100000  merge sort 0.14482 s  sorted 0.01450 s

Source

Sorting Techniques – Python documentation

heapq.merge – Python documentation

In this article we have implemented merge sort in Python and used merging to count inversions and to sort a file. See also Python quick sort, Python heap sort, Python insertion sort, and Python sorted function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.