algorithm analysis
Algorithm Correctness Proofs
You should know: mathematical induction
Overview
Proving an algorithm correct means showing it produces the right output for every valid input, not just the test cases you happened to check. The two workhorse techniques are loop invariants (for iterative algorithms) and induction (for recursive algorithms) — both are really the same idea in different clothes: establish a property that starts true, stays true through each step, and implies correctness once the process finishes.
Intuition
A loop invariant is a statement that's true before the loop starts, stays true after every iteration, and — combined with the fact that the loop eventually stops — implies the loop did what you wanted. It's exactly mathematical induction applied to a running program: the invariant is your 'induction hypothesis', and each loop iteration is an 'inductive step'.
Formal Definition
A loop invariant proof has three parts:
Derivation
Proving correctness of a loop that finds the maximum of an array a[0..n-1]:
Properties
Recursive correctness via induction
Applications
Worked Examples
Base case: interval of size 0 correctly reports 'not found'.
Inductive step: assume binary search is correct on any interval smaller than n. On an interval of size n, comparing to the midpoint either finds the target or recurses into a strictly smaller interval, which is correct by the inductive hypothesis.
Answer: Correct by strong induction on interval size.
Practice Problems
State the loop invariant that proves insertion sort correctly sorts an array.
A loop computes s = 0; for i = 1..n: s = s + i. Give a loop invariant that proves it returns n(n+1)/2, and verify the three invariant steps.
What loop invariant proves binary search is correct, and why does it guarantee termination?
Your sorting function passes 10,000 random test cases. What does this establish about its correctness?
Common Mistakes
Testing an algorithm on several examples counts as a proof of correctness.
Passing test cases only shows the algorithm works on THOSE inputs. A correctness proof must hold for every valid input, including edge cases (empty input, all-equal elements, maximum size) that testing might miss.
Forgetting to separately prove termination (that the loop/recursion actually ends).
A loop invariant alone only shows PARTIAL correctness (if it ends, the answer is right) — you must also argue TERMINATION (e.g. a strictly decreasing, bounded-below quantity) for TOTAL correctness.
Quiz
Summary
- Correctness proofs show an algorithm is right for ALL valid inputs, not just tested cases.
- Loop invariants: a property true at initialization, maintained by each iteration, and useful at termination.
- Recursive algorithms are proved correct by induction: base case + inductive step assuming smaller subproblems are correct.
- Full correctness requires proving BOTH partial correctness (right answer if it halts) and termination (it does halt).
Mathematics