Sub topic 4
Putting It Together: Recursive Merge Sort
This chapter assumes you can read Python, follow a recursive call on the call stack, and use list slicing. It also builds on the two previous chapters: the linear-time merge function, and the idea of splitting a list until each piece has at most one element. Here those two parts combine into a complete sorting function.
The Complete Implementation
Merge sort fits in three steps. If the list has zero or one element, it is already sorted. Otherwise, split it at the midpoint and sort each half recursively. Then merge the two sorted halves.
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]This version always returns a new list and never changes its input. The base case returns list(items) rather than items, so the caller never gets back a reference to its own list. That matters if the caller later modifies the result.
Tracing the Recursion
The work happens in two phases. On the way down, the calls only split lists. On the way back up, each return hands a sorted list to its parent, and the parent merges the two lists it receives.
Python evaluates merge_sort(items[:mid]) completely before it starts merge_sort(items[mid:]). The left subtree is fully sorted before the right subtree is touched, which makes this a depth-first, post-order traversal. At any moment the call stack holds only one root-to-leaf path, so the depth is about log₂ n frames.
For a list of n elements there are exactly n leaves and n − 1 calls to merge. Each internal node of the tree corresponds to one merge.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Base case `len(items) == 1` | `RecursionError` on an empty list | Use `len(items) <= 1` |
| `mid = len(items) // 2 + 1` | Two-element lists split into `[a, b]` and `[]`, so the recursion never shrinks | Use `len(items) // 2` |
| Calling `merge(items[:mid], items[mid:])` without recursing | Output is not sorted, because `merge` needs sorted inputs | Merge the results of the recursive calls |
| Comparing with `<` in `merge` | Still sorts, but equal elements can change order | Keep `<=` (covered in the stability chapter) |
A Note on Slicing
Each slice items[:mid] copies its elements. This keeps the code short, and it does not change the overall growth rate. Production versions pass lo and hi indices into one shared buffer instead. The chapter on auxiliary space covers that technique.
Exercise
If the base case is changed to if len(items) == 1:, what happens when you call merge_sort([])?
Show answer
For an empty list, mid is 0, and both items[:0] and items[0:] are empty. The function calls itself on [] forever and eventually raises RecursionError. The <= 1 check handles the empty list as a base case.
Exercise
How many times is merge called when sorting a list of 7 elements, and how many when sorting 1,000 elements?
Show answer
The recursion tree has n leaves and n − 1 internal nodes, and each internal node does one merge. That gives 6 calls for 7 elements and 999 calls for 1,000 elements.