Skip to content
Visual explainer 2h 30m to learn 4 steps

Merge sort

Implement merge sort and explain its guaranteed O(n log n) time and O(n) extra space.

By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.

Topic 21 of 54

In short

Merge sort splits the array in half, sorts each half recursively and merges the two sorted halves in linear time. It always runs in O(n log n) and is stable, but the standard version needs O(n) extra memory. It is the go-to choice for linked lists and external sorting.

Explained simply

Merge sort uses one simple idea: merging two lists that are already sorted is easy. Look at the front of each list, take the smaller item, and repeat. You never have to look back.

So merge sort splits the list in half, then splits each half, and keeps going until every piece has one item. A list of one item is already sorted. Then it merges pairs of pieces back together, step by step, into bigger and bigger sorted lists.

Splitting in half again and again takes about log2 n rounds. Each round of merging touches every item once. So the total work is about n times log n. For a million items that is roughly 20 million steps, instead of a trillion for the simple sorts.

Merge sort is predictable: it takes the same time whether the input is sorted, reversed or random. It is also stable, keeping equal items in their original order. Its main cost is memory: it needs extra space about the size of the input to do the merging.

Press Play on a diagram to walk through it one step at a time.

MapSplitting [5, 2, 4, 1]
[5, 2, 4, 1]
  • [5, 2] merges to [2, 5]
    • [5]
    • [2]
  • [4, 1] merges to [1, 4]
    • [4]
    • [1]
  • Final merge
    • [1, 2, 4, 5]
SequenceMerging [1, 4] with [2, 3]
Left [1, 4]
Right [2, 3]
Output
  1. 11 < 2: take 1
    Left [1, 4] to Output: 1 < 2: take 1
  2. 22 < 4: take 2
    Right [2, 3] to Output: 2 < 4: take 2
  3. 33 < 4: take 3
    Right [2, 3] to Output: 3 < 4: take 3
  4. 4right empty: copy 4
    Left [1, 4] to Output: right empty: copy 4

In depth

The merge step in detail

Keep two indexes, i into the left list and j into the right list. Compare left[i] and right[j]; append the smaller to the output and move that index forward. When one list runs out, copy the rest of the other.

Each comparison outputs exactly one item, so merging lists of sizes p and q takes at most p + q - 1 comparisons and exactly p + q writes. That is O(n) for the merge.

Stability comes from tie-breaking. On equal values, take from the left list first (left[i] <= right[j]). Because the left half came earlier in the original order, equal items stay in order.

An in-place merge without extra memory is possible but complicated and slower, so practical merge sorts accept O(n) extra space. A common optimisation is skipping the merge entirely when left[-1] <= right[0], because the two halves are already in order. That makes merge sort run in O(n) on already sorted input.

  • At most p + q - 1 comparisons
  • Ties go to the left half for stability
  • Skip the merge if left[-1] <= right[0]

Analysing the recursion tree

The recurrence is T(n) = 2T(n/2) + O(n). Draw the tree: the top level merges n items. The next level has two merges of n/2 items, n in total. Every level does n work, and there are log2 n levels of splitting. So the total is n log2 n.

This holds for every input, because the splits always happen at the middle, no matter what the values are. Best, average and worst cases are all Theta(n log n) for the basic version.

Space has two parts. The merge buffers add up to O(n) at any one time if you reuse one buffer (the slicing version in the explainer allocates new lists each level, which is still O(n) live memory but more garbage). The recursion depth is log2 n, so the stack is O(log n). For n = 10^6, that is only 20 levels, far under Python's recursion limit.

LayersWork per level for n = 8
  1. 1
    Level 0

    1 merge of 8 items: 8 writes

  2. 2
    Level 1

    2 merges of 4 items: 8 writes

  3. 3
    Level 2

    4 merges of 2 items: 8 writes

  4. 4
    Level 3

    8 single items: nothing to merge

  5. 5
    Total

    3 levels x 8 = 24 writes = n log2 n

Bottom-up merge sort

You do not need recursion at all. Treat each item as a sorted run of width 1. Merge neighbouring runs into runs of width 2, then 4, then 8, until one run covers the whole array. That is ceil(log2 n) passes, each O(n).

The bottom-up version avoids the recursion stack and slicing, and it works well with one auxiliary buffer: each pass reads from one array and writes into the other, then they swap roles.

It is also the natural way to merge sort a linked list. Merging two linked lists only relinks next pointers, so no extra array is needed. Bottom-up merge sort on a linked list runs in O(n log n) time with O(1) extra space, which is why it is the standard way to sort linked lists. The last run may be shorter than the others when n is not a power of two; the merge handles uneven sizes naturally.

  • Widths 1, 2, 4, 8 ... until width >= n
  • ceil(log2 n) passes of O(n)
  • Linked lists: O(1) extra space

Merge sort in the real world

Python's list.sort and sorted use Timsort, a merge sort that first finds runs already in order (ascending, or strictly descending, which it reverses), extends short ones with insertion sort, and merges them smartly. It uses a galloping mode that skips quickly through long stretches when one run keeps winning. Java uses Timsort for sorting objects, where stability is required.

External sorting handles data bigger than memory, like a 100 GB file with 8 GB of RAM. Read chunks that fit in memory, sort each and write it to disk as a sorted run. Then do a k-way merge: keep a min-heap with the front item of each run, repeatedly output the smallest, and refill from its run. Each item is read and written a small number of times, and disk reads are sequential, which disks handle well.

Python provides heapq.merge(*iterables) for lazily merging already sorted inputs.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Split recursively to single elements~40m
  2. 2
    Merge two sorted halves~40m
  3. 3
    Analyse the recursion tree~40m
  4. 4
    Implement a bottom-up variant~40m

Key points

  • Time: O(n log n) best, average and worst.
  • Space: O(n) auxiliary for arrays; O(log n) stack.
  • Stable when the merge takes from the left half on ties.
  • Merging k sorted lists generalises the merge step with a heap.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def merge_sort(a):                # O(n log n) time, O(n) space
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:   # <= keeps it stable
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

print(merge_sort([5, 2, 4, 6, 1, 3]))

Bottom-up merge sort with one buffer

For [5, 2, 4, 6, 1, 3], width 1 merges pairs: [2, 5, 4, 6, 1, 3]. Width 2 merges runs of two: [2, 4, 5, 6, 1, 3]. Width 4 merges [2, 4, 5, 6] with [1, 3]: [1, 2, 3, 4, 5, 6]. Width 8 is larger than n, so we stop. Three passes, each O(n), no recursion.

python
def merge_sort_bu(a):
    n, src, dst, width = len(a), a[:], [None] * len(a), 1
    while width < n:
        for lo in range(0, n, 2 * width):
            mid, hi = min(lo + width, n), min(lo + 2 * width, n)
            i, j = lo, mid
            for k in range(lo, hi):
                if j >= hi or (i < mid and src[i] <= src[j]):
                    dst[k] = src[i]; i += 1
                else:
                    dst[k] = src[j]; j += 1
        src, dst = dst, src
        width *= 2
    return src

print(merge_sort_bu([5, 2, 4, 6, 1, 3]))  # [1, 2, 3, 4, 5, 6]

Merging k sorted files with heapq.merge

Imagine three log files, each already sorted by timestamp. heapq.merge keeps one item from each input in a small heap and yields the smallest each time. It never loads everything into memory, and with k inputs each output step costs O(log k). Total time for N items is O(N log k). The key argument works just like in sorted().

python
import heapq

log_a = [(1, 'a: start'), (5, 'a: done')]
log_b = [(2, 'b: start'), (3, 'b: retry'), (9, 'b: done')]
log_c = [(4, 'c: start')]

for ts, msg in heapq.merge(log_a, log_b, log_c):
    print(ts, msg)
# 1 a: start / 2 b: start / 3 b: retry / 4 c: start / 5 a: done / 9 b: done

Quick reference

  • Time: Theta(n log n) best, average and worst for the basic version
  • Extra space: O(n) buffer plus O(log n) recursion stack
  • Stable when ties take from the left half (<=)
  • Skip the merge when left[-1] <= right[0]: sorted input becomes O(n)
  • Bottom-up: merge widths 1, 2, 4 ... for ceil(log2 n) passes, no recursion
  • Linked lists: merge sort in O(n log n) time and O(1) extra space
  • heapq.merge(*sorted_iterables) merges lazily in O(N log k)

Common mistakes

  • Using < instead of <= in the merge, losing stability.
  • Forgetting to append the leftover tail of one half.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1How many comparisons can merging two sorted lists of sizes 4 and 6 take at most?

Question 2

2Why is merge sort's worst case the same as its best case?

Question 3

3How many passes does bottom-up merge sort make on 1,000 items?

Question 4

4Which task is merge sort especially suited to?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write merge(a, b) that merges two sorted lists into one sorted list without calling sort. Example: merge([1, 3, 5], [2, 4]) gives [1, 2, 3, 4, 5].

  2. Exercise 2medium

    Given a linked list built from class Node(val, next), write merge_lists(a, b) that merges two sorted lists by relinking nodes, without creating new nodes except one dummy head.

  3. Exercise 3hard

    Write sort_list(head) that merge sorts a linked list top-down: find the middle with slow and fast pointers, split, sort each half, and merge with merge_lists. Time O(n log n).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is merge sort faster than quicksort?
Both are O(n log n) on average. Quicksort is often faster on arrays because it works in place with good cache use, while merge sort wins when you need stability, guaranteed worst-case time, linked lists or external data.
Does Python use merge sort?
Python uses Timsort, a hybrid of merge sort and insertion sort that finds existing sorted runs. It is stable and runs in O(n log n) worst case and O(n) on already sorted data.
Can merge sort be done in place?
In-place merging algorithms exist, but they are complex and much slower in practice. Standard implementations use an O(n) buffer.

Go deeper

ShareXLinkedInWhatsApp