Sub topic 8
Merge Sort: The Canonical Example
This chapter assumes you can trace recursive functions, read Big-O notation, and apply the master theorem from the earlier chapters. Merge sort is the standard example of divide and conquer because each of its three steps is easy to see.
The Three Steps
- Divide: split the list at its midpoint into a left half and a right half. This takes constant time if you track indices, or linear time if you copy slices as the code below does.
- Conquer: sort each half recursively. A list of length 0 or 1 is already sorted, so that is the base case.
- Combine: merge the two sorted halves into one sorted list. All of the real work happens in this step.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
return merge(left, right)
def merge(left, right):
out = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
print(merge_sort([5, 2, 9, 1, 5, 6])) # [1, 2, 5, 5, 6, 9]How the Merge Works
The merge keeps one pointer into each sorted half. At each step it compares the two front elements and appends the smaller one. When one half runs out, everything left in the other half is already sorted and larger than what has been output, so extend copies the rest in one go. Each element is appended exactly once, so merging lists of total length n costs O(n).
To see that the merge is correct, note that the output is always the smallest elements seen so far, in sorted order. Once you know the merge is correct, induction on list length shows that the whole sort is correct.
Running Time
Two half-size subproblems plus a linear combine step give:
T(n) = 2T(n/2) + O(n)
Here a = 2, b = 2, and f(n) = Θ(n) = Θ(n^(log₂ 2)), which is case 2 of the master theorem. So T(n) = Θ(n log n). The recursion tree gives the same result: there are about log₂ n levels, and each level does O(n) total merge work.
| Property | Merge sort |
|---|---|
| Best, average, worst time | Θ(n log n) |
| Extra space | Θ(n) for merge buffers |
| Stable | Yes, when ties take from the left half |
| Input order sensitivity | None |
Common Errors
- Splitting with
mid = len(a) // 2but recursing ona[:mid + 1]: a list of length 2 then never shrinks, and the recursion never ends. - Forgetting the leftover
extendcalls: the elements remaining after the loop are silently dropped. - Assuming slicing is free: in Python,
a[:mid]copies the slice. That adds O(n) work per level, which does not change the Θ(n log n) bound but does add memory traffic.
Exercise
Suppose you split the list into three equal parts, sort each recursively, and merge all three in linear time. Write the recurrence and solve it.
Show answer
T(n) = 3T(n/3) + O(n). Here log₃ 3 = 1 matches f(n) = Θ(n), so case 2 gives Θ(n log n). The base of the logarithm changes, but the asymptotic bound does not.
Exercise
Trace merge([1, 4, 7], [2, 3, 8]). How many comparisons are made before the loop ends?
Show answer
The loop compares 1 vs 2 (take 1), 4 vs 2 (take 2), 4 vs 3 (take 3), 4 vs 8 (take 4), and 7 vs 8 (take 7). The left half is now empty, so the loop stops after 5 comparisons and extend appends 8. The result is [1, 2, 3, 4, 7, 8].