Algorithm Correctness Lab
Retrieval Prompts
- State the three parts of a loop-invariant proof.
- State the schema for a recursive correctness proof by strong induction.
- Define a termination variant and explain what "well-founded" means.
- Why is testing not a substitute for a correctness proof?
- What goes wrong in a recursive proof if the inductive hypothesis is assumed only for
n - 1when the function recurses onn / 2?
Compare and Distinguish
Separate these pairs:
- loop invariant versus postcondition
- correctness proof versus termination proof
- strong induction versus ordinary induction
- "the algorithm works" versus "the algorithm terminates"
Common Mistake Check
Identify the error:
- "My invariant is that the array will be sorted after the loop ends."
- "I proved correctness by running the algorithm on 50 random inputs and it always worked."
- "My recursive function calls itself on
n - 1or onndepending on the branch; termination is obvious." - "I do not need a base case because the inductive step handles everything."
- "The loop terminates because the index variable changes every iteration."
Mini Application
Loop invariant proofs
Write a loop invariant, then prove initialization, maintenance, and termination for each:
-
linear_search(A, x): returns an indexiwithA[i] == x, or-1if none. -
max_of(A): returns the maximum element of a non-empty array. -
The Lomuto partition step:
def partition(A, lo, hi):
pivot = A[hi]
i = lo - 1
for j in range(lo, hi):
if A[j] <= pivot:
i += 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[hi] = A[hi], A[i + 1]
return i + 1Invariant should describe
A[lo..i],A[i+1..j-1], andA[j..hi-1].
Recursive induction proofs
For each, state the induction hypothesis explicitly and prove the base and inductive steps:
power(x, n)computingx^nbyx * power(x, n-1), basepower(x, 0) = 1.- Binary search on a sorted array.
- Recursive
merge_sort(you may assumemergeis correct as a lemma).
Termination arguments
Give a decreasing variant and justify well-foundedness:
- Euclid's
gcd(a, b) = gcd(b, a mod b). - The recursive
merge_sort. - A DFS on a finite graph using a visited set.
- A loop
while lo <= hi:in binary search.
Evidence Check
This page is complete only if, for any code you have written this module, you can produce:
- a loop invariant or induction hypothesis in one sentence
- a proof sketch of initialization, maintenance, and termination (or base case and inductive step)
- a termination variant with a written argument for why it strictly decreases