Sub topic 4
Putting It Together: Recursive Merge Sort
This chapter assumes you can read Python, follow a recursive function through the call stack, and use Big-O notation. It also assumes you have read the two previous chapters. One covered the linear-time merge of two sorted lists. The other covered splitting a list in half until a single element remains. Here we join those two pieces into a complete sorting function. We then trace it by hand, look at the order in which the calls run, and go through the mistakes people make most often when they write it.
The Complete Function
Merge sort has two parts. The merge function does the real work of putting elements in order. The merge_sort function decides where to split and when to stop.
def merge(left, right):
result = []
i = j = 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
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort(items):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge(merge_sort(items[:mid]), merge_sort(items[mid:]))
print(merge_sort([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]The body of merge_sort is three lines, and each line has one job:
- Base case. A list with zero or one element is already sorted. The function returns a copy, so the caller always gets a new list that it owns.
- Divide.
mid = len(items) // 2picks the split point. For odd lengths the left half gets one fewer element than the right. - Conquer and combine. The function sorts each half recursively and passes both results to
merge.
All the comparisons happen inside merge. merge_sort never compares two elements. It only breaks the problem into pieces that merge can handle, and it relies on one guarantee: when merge is called, both of its inputs are already sorted.
Tracing a Run by Hand
Here is the call for [38, 27, 43, 3, 9, 82, 10]. The length is 7, so mid is 3. The left half is [38, 27, 43] and the right half is [3, 9, 82, 10].
The tree shows the structure, but Python does not build it one level at a time. In the expression merge(merge_sort(left), merge_sort(right)), Python evaluates the arguments from left to right. So the whole left subtree is sorted before the right subtree is even split. The run is depth-first:
| Step | Event | Result |
|---|---|---|
| 1 | Split `[38, 27, 43]` into `[38]` and `[27, 43]` | `[38]` returns at once |
| 2 | Split `[27, 43]` into `[27]` and `[43]` | both are base cases |
| 3 | Merge `[27]` and `[43]` | `[27, 43]` |
| 4 | Merge `[38]` and `[27, 43]` | `[27, 38, 43]` |
| 5 | Split `[3, 9, 82, 10]` into `[3, 9]` and `[82, 10]` | |
| 6 | Split and merge `[3, 9]` | `[3, 9]` |
| 7 | Split and merge `[82, 10]` | `[10, 82]` |
| 8 | Merge `[3, 9]` and `[10, 82]` | `[3, 9, 10, 82]` |
| 9 | Merge `[27, 38, 43]` and `[3, 9, 10, 82]` | `[3, 9, 10, 27, 38, 43, 82]` |
Depth-first order matters for memory. At any moment, the only frames on the call stack are the ones on a single path from the root to a leaf. That path has about log₂ n frames, so the recursion is shallow. For a million elements the depth is about 20, far below Python's default recursion limit of 1000. A later chapter counts the total memory in detail.
Counting the Calls
Each call either hits the base case (a leaf) or makes exactly two recursive calls. With n ≥ 1 elements, the splits stop at n single-element lists, so there are n leaves. A binary tree where every internal node has two children and there are n leaves has n − 1 internal nodes. That gives 2n − 1 calls to merge_sort in total and n − 1 calls to merge. In the example, n = 7, so there are 13 calls to merge_sort and 6 merges, which matches the 6 merge boxes in the diagram.
These counts show that the overhead of the recursion itself is linear. The n log n cost comes from the merges, as the chapter on the recurrence will show.
Common Mistakes
A base case that misses the empty list
A frequent bug is writing if len(items) == 1: as the base case. It works for most inputs, but merge_sort([]) then computes mid = 0 and calls merge_sort([]) on both halves. Those calls do the same thing again, and the program stops with RecursionError. With <= 1, both the empty list and single-element lists end the recursion.
A split that can produce an empty half and a full half
The split has to make progress: both halves must be strictly shorter than the input. len(items) // 2 meets that rule for every length of 2 or more. Something like mid = (len(items) + 1) // 2 also works. But a split that can return 0 or len(items) for some length passes the whole list to one recursive call. That call never shrinks the list and recurses forever.
Expecting the input to be sorted in place
This version returns a new list and leaves the argument unchanged:
data = [5, 1, 4]
merge_sort(data)
print(data) # [5, 1, 4] (unchanged)
data = merge_sort(data)
print(data) # [1, 4, 5]If you call it the way you would call list.sort(), the result is thrown away. Choose one contract, either "return a new list" or "mutate the argument", and keep to it.
Replacing `<=` with `<` in the merge
With <, the output is still sorted. But when two elements are equal, the merge takes the one from the right half first, so equal elements can swap their original order. That breaks stability, which has its own chapter. For now, keep <=.
Returning `items` instead of a copy in the base case
If the base case returns items itself, no bug shows up here, because slicing already makes copies. The danger comes when you rewrite the function to work on index ranges or to mutate its inputs. Then a caller can end up holding an alias to the original list. Returning list(items) keeps the contract simple: every call returns a list nobody else holds.
The Hidden Cost of Slicing
items[:mid] and items[mid:] each copy their part of the list, and every merge builds a new result list. The asymptotic running time stays the same, because copying a level costs O(n), which is the same as merging it. But the code allocates many short-lived lists. A common alternative passes index bounds and uses one shared buffer:
def merge_sort_range(a):
buf = [None] * len(a)
_sort(a, buf, 0, len(a))
return a
def _sort(a, buf, lo, hi):
if hi - lo <= 1:
return
mid = (lo + hi) // 2
_sort(a, buf, lo, mid)
_sort(a, buf, mid, hi)
i, j, k = lo, mid, lo
while i < mid and j < hi:
if a[i] <= a[j]:
buf[k] = a[i]
i += 1
else:
buf[k] = a[j]
j += 1
k += 1
while i < mid:
buf[k] = a[i]
i += 1
k += 1
while j < hi:
buf[k] = a[j]
j += 1
k += 1
a[lo:hi] = buf[lo:hi]
data = [38, 27, 43, 3, 9, 82, 10]
merge_sort_range(data)
print(data) # [3, 9, 10, 27, 38, 43, 82]The half-open range [lo, hi) makes the code simpler. The halves are [lo, mid) and [mid, hi), they never overlap, and the base case hi - lo <= 1 covers empty ranges too. This version sorts a in place from the caller's point of view, but it still needs the O(n) buffer. The space chapter explains why an array merge cannot easily avoid that buffer.
| Version | Allocations | Mutates input | Easiest to read |
|---|---|---|---|
| Slicing (`merge_sort`) | New lists at every call | No | Yes |
| Index range (`merge_sort_range`) | One buffer of size n | Yes | Less so |
Edge Cases to Test
A short test list catches most bugs in a hand-written merge sort:
import random
cases = [
[],
[1],
[2, 1],
[1, 2, 3, 4],
[4, 3, 2, 1],
[5, 5, 5, 5],
[3, -1, 0, -1, 3],
["pear", "apple", "fig"],
]
cases += [[random.randint(-50, 50) for _ in range(n)] for n in range(0, 60)]
for c in cases:
assert merge_sort(c) == sorted(c), c
copy = list(c)
assert merge_sort_range(copy) == sorted(c), c
print("all tests passed")The cases cover the empty list, a single element, inputs already in order and in reverse order, all-equal values, negative numbers, and non-numeric values. The random lists of every length from 0 to 59 check both odd and even splits. Comparing against sorted gives a trusted reference.
Exercise
If you change the base case to if len(items) == 1:, what does merge_sort([]) do, and why? What about merge_sort([7])?
Show answer
merge_sort([]) raises RecursionError. With length 0, mid is 0, and both halves are empty lists, so each recursive call gets the same empty input and never reaches a base case. merge_sort([7]) still works, because length 1 matches the base case. The bug only affects empty input, including any empty half that a split might produce.
Exercise
For an input of 10 elements, how many times is merge_sort called in total, and how many times is merge called? Does the answer depend on the values?
Show answer
It is called 2n − 1 = 19 times and merge is called n − 1 = 9 times. The counts depend only on the length, because the split points come from len(items) // 2 and never from comparing values.
Exercise
Add an optional key parameter to merge_sort (and merge) so that merge_sort(words, key=len) sorts strings by length while keeping equal-length strings in their original order. What is the one comparison you must change?
Show answer
Pass key through every recursive call and into merge, and change the comparison to if key(left[i]) <= key(right[j]):. Keep <= so equal keys come from the left half first and their order is preserved. Use a default of key=lambda x: x. For example, merge_sort(["ccc", "a", "bb", "d"], key=len) returns ["a", "d", "bb", "ccc"].
Exercise
In merge_sort_range, why does _sort write into buf and then copy back, instead of writing merged values straight into a?
Show answer
While merging, a[lo:hi] still holds the two halves being read. If merged values were written straight into a, they could overwrite elements of the left half that have not been read yet. That would lose data. The buffer keeps the inputs intact until the merge is finished.