Sub topic 12
Divide and Conquer: Merge Sort
This chapter assumes you can read Python functions, know how list slicing works, and are comfortable trusting a recursive call to return the right answer for a smaller input, as covered in the chapter on thinking recursively.
The Divide-and-Conquer Pattern
Divide and conquer solves a problem in three steps:
- Divide the input into smaller pieces of the same kind.
- Conquer each piece by solving it recursively.
- Combine the partial results into a full answer.
Merge sort applies this pattern to sorting. A list of length 0 or 1 is already sorted, so that is the base case. Any longer list is split in half, each half is sorted recursively, and the two sorted halves are merged into one sorted list.
The Implementation
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
print(merge_sort([5, 2, 9, 1, 3])) # [1, 2, 3, 5, 9]Apply the leap of faith to the two recursive calls. You don't trace them. You assume left and right come back sorted. The only new work at each level is the merge. The merge walks both lists with indices i and j and always takes the smaller front element. When one list runs out, the rest of the other list is already sorted and gets appended in one step.
Watching It Split and Merge
Each level of splitting halves the list sizes, so there are about log₂ n levels. Across one level, the merges touch every element once, which costs O(n). The cost follows the recurrence T(n) = 2T(n/2) + O(n), which works out to O(n log n) time. A later chapter shows how to solve recurrences like this one. The recursion is only about log₂ n calls deep, so merge sort is in no danger of hitting stack limits.
Common Errors
| Mistake | Consequence |
|---|---|
| Base case `len(items) == 1` | An empty list splits into two empty lists forever, which raises `RecursionError` |
| Forgetting the two `extend` calls | Leftover elements are silently dropped |
| Using `<` instead of `<=` in the merge | The result is still sorted, but equal elements can swap order, so the sort is no longer stable |
| Splitting with `mid = len(items) // 2 + 1` on a 2-element list | `items[mid:]` is empty and the left half never shrinks |
Exercise
If you change the base case to if len(items) == 1: and call merge_sort([]), what happens and why?
Show answer
It raises RecursionError. With an empty list, mid is 0, so both items[:0] and items[0:] are empty lists. The function calls itself on an empty list again and never reaches a base case.
Exercise
For a list of 16 elements, how many levels of splitting occur before every piece has length 1, and roughly how many element comparisons or copies happen per level?
Show answer
There are 4 levels, because log₂ 16 = 4. Each level's merges together process all 16 elements, so the work is about 16 per level, or about 64 in total. This matches n log n.