Sub topic 5
Why Merge Sort Is Correct
This chapter assumes you know the merge and merge_sort functions from the previous chapters, that you can read recursive Python, and that you have seen proof by induction at least once. The goal is to argue that merge_sort returns a sorted list for every input, without testing every possible input.
What "correct" means here
A sort is correct when its output has two properties:
- Sorted: each element is less than or equal to the one after it.
- Permutation: the output contains exactly the same elements as the input, with the same counts.
It is easy to forget the second property. A function that always returns [] produces sorted output, but it is clearly wrong.
Step 1: the merge is correct
The claim is this: if left and right are both sorted, then merge(left, right) returns a sorted permutation of their combined elements.
The proof uses a loop invariant, which is a statement that is true before every iteration of the while loop:
resultholds thei + jsmallest elements ofleft + right, in sorted order.- Every element in
resultis less than or equal to every element not yet taken.
Before the first iteration, result is empty, so the invariant holds trivially. On each iteration, the smallest remaining element must be either left[i] or right[j], because both lists are sorted. The loop appends the smaller of the two, so the invariant still holds afterwards. When the loop ends, one list is used up. The rest of the other list is sorted, and each of its elements is at least as large as everything already in result, so extending result with it keeps everything in order. Every element is appended exactly once, so the output is a permutation of the input.
Step 2: merge sort is correct, by strong induction
The induction is on n = len(items). The hypothesis is that merge_sort correctly sorts every list shorter than n.
- Base case (n ≤ 1). The function returns
list(items). A list with zero or one element is already sorted, and the copy contains the same elements. - Inductive step (n ≥ 2). The function sets
mid = n // 2. Because n ≥ 2, we have 1 ≤ mid < n, so both halves are non-empty and strictly shorter thann. By the hypothesis, both recursive calls return sorted permutations of their halves. Step 1 then shows that merging them gives a sorted permutation of the whole list.
The fact that both halves are strictly shorter than n also proves that the recursion terminates. The length goes down on every call, so every chain of calls eventually reaches the base case.
Where the proof catches real bugs
Each step of the proof matches a line of code. Changing one of those lines breaks the proof, and usually breaks the program too.
| Bug | Which part of the proof fails | Symptom |
|---|---|---|
| Base case `len(items) == 1` | An empty list is never handled: `mid = 0`, so the right half is the whole list again | `RecursionError` on `[]` |
| `mid = (n + 1) // 2` with base case `n == 0` | When n = 1, `mid` is 1, so the left half is not shorter | Infinite recursion |
| Forgetting `result.extend(...)` | The permutation property fails | Elements go missing |
| Using `<` instead of `<=` | The output is still sorted and still a permutation, so correctness holds | Stability is lost (next chapter) |
A proof does not replace testing, but a randomized check against Python's built-in sorted is a cheap way to back it up:
import random
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:]))
for _ in range(1000):
data = [random.randint(-5, 5) for _ in range(random.randint(0, 20))]
assert merge_sort(data) == sorted(data), data
print("all tests passed")The small value range (-5 to 5) forces many duplicates, and the lengths include 0 and 1, so the test exercises the edge cases the proof depends on.
Exercise
Someone changes the base case to if len(items) == 1: return list(items). Which input breaks the function, and which assumption of the inductive proof no longer holds?
Show answer
The empty list breaks it. With n = 0, mid = 0, so items[mid:] is the empty list again. That recursive call is not on a strictly shorter list, so both the inductive step (halves shorter than n) and the termination argument fail, and the function raises RecursionError. Non-empty inputs never produce an empty half, because mid is at least 1 when n is at least 2.
Exercise
In the merge proof, why is it safe to append the rest of the unfinished list without comparing it to anything?
Show answer
The loop invariant says every element in result is less than or equal to every element not yet taken. The leftover elements come from one sorted list, so they are already in order among themselves, and each is at least as large as everything in result. Appending them keeps the whole output sorted.