Sub topic 5
Why Merge Sort Is Correct
Earlier chapters built merge and merge_sort and traced them on examples. Examples can show that code works on the inputs you tried. They cannot show that it works on every input. This chapter gives an argument that covers all inputs. First we prove that merge is correct using a loop invariant. Then we prove that merge_sort is correct using strong induction on the length of the input.
This chapter assumes you are comfortable with Python lists and slicing, with recursion and base cases, and with the idea of mathematical induction (prove a base case, then prove that each case follows from smaller ones). Running time and stability are covered in later chapters, so they appear here only when they affect correctness.
What "correct" means for a sort
A sorting function is correct when, for every input list items, it returns a list that has two properties:
- Sorted: every 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 number of copies of each. Nothing is lost, duplicated, or invented.
Both properties matter. A function that always returns [] produces sorted output and is useless. Many real bugs in merge code produce output that is sorted but missing elements, which is why we check the permutation property separately.
A full proof also needs termination: the function must return at all. A recursive function that never reaches its base case never returns a wrong answer, and it never returns a right one either.
Proving the merge step correct
Here is the merge from the earlier chapter:
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 resultPrecondition: left and right are each sorted. Postcondition: the returned list is sorted and is a permutation of left + right.
The loop invariant
A loop invariant is a statement that is true before the loop's first iteration and stays true after every iteration. For merge it is this:
At the start of each iteration of the while loop:
- (a)
resultcontains exactly the elements ofleft[:i]andright[:j], each once. - (b)
resultis sorted. - (c) If
resultis non-empty, its last element is less than or equal toleft[i]and toright[j].
Part (c) carries most of the proof. It says that everything already placed is no larger than anything still waiting.
Initialization
Before the first iteration, i = j = 0 and result = []. The slices left[:0] and right[:0] are empty, so (a) holds. An empty list is sorted, so (b) holds. Part (c) applies only when result is non-empty, so it holds trivially.
Maintenance
Suppose the invariant holds at the start of an iteration and left[i] <= right[j]. The code appends left[i] and increments i.
- (a)
resultnow holdsleft[:i+1]andright[:j]. One element moved from "waiting" to "placed", exactly once. - (b) By (c), the old last element was
<= left[i], so appendingleft[i]keepsresultsorted. - (c) The new last element is
left[i]. Becauseleftis sorted,left[i] <= left[i+1]. Becauseleft[i] <= right[j]was the branch condition, it is also<= right[j]. So (c) holds for the new indices.
The else branch is symmetric. There, right[j] < left[i], and sortedness of right gives right[j] <= right[j+1].
The key fact is that the smallest remaining element of a sorted list is always at its front. So the smaller of the two fronts is the smallest remaining element overall.
Termination and the leftovers
Each iteration increases i + j by exactly 1, and i + j cannot exceed len(left) + len(right). So the loop ends. When it does, at least one list is exhausted.
Suppose j == len(right), so right is used up. The remaining slice left[i:] is sorted, because it is part of a sorted list. By (c), the last element of result is <= left[i], which is the smallest leftover element. Appending the leftover slice therefore keeps result sorted. right[j:] is empty, so the second extend adds nothing. The case where left runs out first is symmetric.
After both extend calls, result holds left[:len(left)] and right[:len(right)], which is every element exactly once. The postcondition holds.
Proving merge sort correct by strong induction
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:]))Claim: for every n ≥ 0 and every list items of length n, merge_sort(items) terminates and returns a sorted permutation of items.
We use strong induction on n. In strong induction you may assume the claim holds for every size smaller than n, not just for n − 1. We need that here because the halves have size about n/2, not n − 1.
Base case: n ≤ 1
A list of length 0 or 1 is already sorted. list(items) returns a copy with the same elements. The function returns immediately with no recursion, so it terminates.
Inductive step: n ≥ 2
Assume the claim holds for every length smaller than n. Let mid = n // 2.
- Both halves are strictly smaller. For n ≥ 2,
midis at least 1 and at most n − 1. Soitems[:mid]has lengthmid, which is between 1 and n − 1.items[mid:]has lengthn - mid, which is also between 1 and n − 1. - The recursive calls are correct. By the inductive hypothesis, each call terminates and returns a sorted permutation of its half.
- The merge is correct. Both arguments to
mergeare sorted, so its precondition holds. By the proof above, it returns a sorted permutation of the two halves combined. - The halves partition the input.
items[:mid] + items[mid:]equalsitems. A permutation of a permutation of the halves is a permutation ofitems.
So merge_sort(items) terminates and returns a sorted permutation of items. By strong induction, the claim holds for every n.
Where the proof catches real bugs
Each step of the proof matches a line of code. If you break the line, the proof fails at that step, and the code fails the same way.
| Bug | Proof step that fails | Symptom |
|---|---|---|
| Base case `if len(items) == 0` | Halves strictly smaller: for n = 1, `mid = 0`, so the right half has length 1, the same as n | `RecursionError` on any non-empty input |
| `mid = (len(items) + 1) // 2` with base case `== 0` | Same: for n = 1, `mid = 1`, so the left half has length 1 | `RecursionError` |
| Omit `result.extend(left[i:])` | Merge postcondition (permutation) | Output is sorted but shorter than the input |
| Loop condition `or` instead of `and` | Maintenance: reads `left[i]` after `left` is exhausted | `IndexError` |
| Merge receives unsorted input | Merge precondition | Output not sorted |
The first two rows show why the base case must cover n = 1. The inductive step depends on n ≥ 2 to guarantee that both halves shrink.
Checking the invariant at runtime
A proof is the real guarantee. Executable assertions are still a good way to confirm that your code matches the proof. The version below asserts the loop invariant on every iteration and then checks both correctness properties on thousands of random inputs, including many duplicates.
import random
from collections import Counter
def merge_checked(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
# (a) and (b): result is the sorted contents of left[:i] + right[:j]
assert result == sorted(left[:i] + right[:j])
# (c): everything placed is <= everything still waiting
if result:
assert result[-1] <= left[i] and result[-1] <= right[j]
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
left_half, right_half = items[:mid], items[mid:]
assert 0 < len(left_half) < len(items)
assert 0 < len(right_half) < len(items)
return merge_checked(merge_sort(left_half), merge_sort(right_half))
def is_sorted(xs):
return all(xs[k] <= xs[k + 1] for k in range(len(xs) - 1))
random.seed(1)
for trial in range(3000):
n = random.randint(0, 40)
data = [random.randint(-5, 5) for _ in range(n)]
out = merge_sort(data)
assert is_sorted(out), data
assert Counter(out) == Counter(data), data
print("all checks passed")The Counter comparison checks the permutation property, including duplicate counts. A check that only uses is_sorted would miss the "dropped leftovers" bug from the table.
Exercise
A student writes the base case as if len(items) == 0: return [] and keeps mid = len(items) // 2. Which step of the induction proof fails, and what happens when the function is called on [7]?
Show answer
The step that fails is "both halves are strictly smaller". For n = 1, mid = 0, so items[:0] is [] and items[1-0:] is items[0:] = [7], the same length as the input. The call mergesort([7]) calls mergesort([7]) again, recursing until Python raises RecursionError. The fix is a base case of len(items) <= 1.
Exercise
Why does the proof of merge_sort use strong induction instead of ordinary induction from n - 1 to n?
Show answer
The recursive calls are on lists of length n // 2 and n - n // 2, not n - 1. Ordinary induction only lets you assume the claim for n - 1. Strong induction lets you assume it for every length below n, which covers both halves.
Exercise
In the merge invariant, part (c) says the last element of result is <= left[i] and <= right[j]. Explain which part of the proof would break if left were not sorted, and give a two-element example where merge then returns unsorted output.
Show answer
Maintenance of (c) breaks. After appending left[i], we need left[i] <= left[i+1], which relies on left being sorted. Example: merge([3, 1], [2]). The loop compares 3 and 2 and appends 2. right is now exhausted, so extend adds [3, 1], and the result is [2, 3, 1], which is not sorted.