Sub topic 8
Merge Sort: The Canonical Example
Merge sort is the algorithm most textbooks use to teach divide and conquer, because each of its three steps is easy to see. The divide step is trivial, the conquer step is two recursive calls, and all of the real work happens in the combine step. This chapter assumes you can write and trace recursive Python functions, read Big-O notation, and use the recurrence, recursion tree, and master theorem tools from earlier chapters. It also builds on the half-open ranges [lo, hi) introduced with binary search.
The Three Steps
Merge sort sorts a list as follows:
- Divide: split the list at its midpoint into a left half and a right half. This takes constant time if you work with indices, or linear time if you copy slices.
- Conquer: sort each half by calling merge sort recursively.
- Combine: merge the two sorted halves into one sorted list in linear time.
Binary search throws one half away. Merge sort keeps both halves and pays for that with a linear-time combine step. That difference changes the running time from O(log n) to O(n log n).
The Implementation
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]The base case len(a) <= 1 covers both the empty list and the single-element list, and each of those is already sorted. Every recursive call gets a strictly shorter list whenever len(a) >= 2, because mid then falls between 1 and len(a) - 1. So the recursion always terminates.
How the Merge Step Works
The merge keeps two pointers, i into left and j into right. It relies on this loop invariant:
outholds thei + jsmallest elements ofleft + right, in sorted order.
At each step, the smallest remaining element must be either left[i] or right[j], because each half is sorted. Appending the smaller of the two keeps the invariant true. When one half runs out, everything left in the other half is at least as large as everything in out, so the two extend calls finish the job. Each element is appended exactly once, so merging lists of total length n takes O(n) time.
Stability
A sort is stable if equal elements keep their original relative order. The comparison left[i] <= right[j] takes from the left half on ties, and left-half elements came earlier in the input. That makes merge sort stable. If you change <= to <, the output is still sorted, but ties are taken from the right half and stability breaks. Stability matters when you sort records by one key after sorting them by another. Python's built-in sorted (Timsort) is a merge-sort hybrid and is stable for this reason.
Correctness by Induction
Use strong induction on n = len(a).
- Base case: if n ≤ 1, the function returns
aunchanged, and a list that short is sorted. - Inductive step: if n ≥ 2, both halves are shorter than n, so by the inductive hypothesis the recursive calls return sorted permutations of the halves. By the loop invariant,
mergereturns a sorted permutation of their concatenation, which is a sorted permutation ofa.
Running Time
Let T(n) be the time to sort n elements. The function makes two calls on halves and does linear work for slicing and merging:
T(n) = 2T(n/2) + Θ(n), with T(1) = Θ(1).
Recursion tree view: level k has 2^k subproblems of size n/2^k, so each level does Θ(n) total work. The sizes reach 1 after log₂ n levels, so the total is Θ(n log n).
Master theorem view: a = 2, b = 2, f(n) = Θ(n), and n^(logb a) = n. Here f(n) matches n^(logb a), which is case 2, so T(n) = Θ(n log n).
When n is odd, the halves have sizes ⌊n/2⌋ and ⌈n/2⌉. Floors and ceilings like these do not change the asymptotic result.
Merge sort does Θ(n log n) work on every input, whether sorted, reversed, or random. Unlike quicksort, it has no bad case. The basic version also gets no benefit from input that is already sorted.
| Property | Merge sort (this version) |
|---|---|
| Best, average, worst time | Θ(n log n) |
| Extra space | Θ(n) for merge output, plus O(log n) stack |
| Stable | Yes, with `<=` |
| Recursion depth | ⌈log₂ n⌉ |
| Sorts in place | No |
Avoiding Slice Copies
The slices a[:mid] and a[mid:] copy data on every call. That copying does not change the Θ(n log n) bound, but it allocates many short-lived lists. A common improvement is to sort by index ranges with a single shared buffer:
def merge_sort_indices(a):
buf = [None] * len(a)
def sort(lo, hi):
# Sorts a[lo:hi] in place, using buf as scratch space
if hi - lo <= 1:
return
mid = (lo + hi) // 2
sort(lo, mid)
sort(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]
sort(0, len(a))
return a
print(merge_sort_indices([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]This version allocates Θ(n) extra space once, up front. It follows the same half-open range convention as binary search.
Common Errors
Other mistakes to watch for:
- A base case of only
len(a) == 1. An empty input then recurses forever, becausea[:0]anda[0:]are both empty. - Treating the return value as optional. The slicing version returns a new list and leaves the input unchanged. Calling
merge_sort(a)without using its result has no effect. - Assuming merge sort sorts in place. Standard merge sort on arrays needs Θ(n) auxiliary space. In-place merging exists, but it is complicated and slower in practice.
Exercise
Write the recurrence for a variant of merge sort that splits the list into three equal parts, sorts each recursively, and merges all three in linear time. What is its running time?
Show answer
T(n) = 3T(n/3) + Θ(n). Here n^(log_3 3) = n matches f(n), which is master theorem case 2, so T(n) = Θ(n log n). Only the base of the logarithm changes, and that is a constant factor.
Exercise
Sorting [(1, 'a'), (0, 'b'), (1, 'c')] by the first component only, which output does a stable sort produce, and which line of merge determines this?
Show answer
[(0, 'b'), (1, 'a'), (1, 'c')]. The tie-break left[i] <= right[j] takes the left (earlier) element when keys are equal, so (1, 'a') stays ahead of (1, 'c').
Exercise
How many element comparisons does merge make in the worst case when merging two sorted lists of lengths p and q, and when does that happen?
Show answer
p + q - 1 comparisons. This happens when the last elements of the two lists are the two largest overall, so neither list runs out until only one element is left.