Loop Invariants
Good name — what does it do?
Running time?
Does it work?
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 32 | 11 | 73 | 21 | 29 | 86 | 81 | 92 | 57 | 61 | 64 | 15 | 79 | 44 | 7 | 45 |
What are the possible values of \(i\)?
Stop the algorithm at some iteration \(i\) — what do we know about the variables?
Thm. idxOfMin(C, a) returns the index of the minimum value in C[a..n-1].
We want, at exit: retloc is the index of the min of C[a..n-1].
So carry that claim through the loop:
Loop invariant. At the start of iteration \(i\), retloc is the index of the minimum value in C[a..___].
Loop invariant. At the start of iteration \(i\), retloc is the index of the minimum value in C[a..___].
Proving the Theorem requires three things:
| Initialization | the invariant is true before the first iteration |
| Restoration | if true at the start of iteration \(i\), it is true at the start of \(i+1\) |
| Termination | the loop ends — and invariant + exit condition give the theorem |
What does this smell like?
Initialization. \(i = a{+}1\):
Restoration. Assume invariant holds at the top of \(i\), and then run the body:
Does the loop stop?
What is the state when it does?
| 1. Recognize the Claim | the postcondition you are trying to reach |
| 2. Find an invariant | strong enough to give that at exit, and still true after one pass |
| 3. Initialization | true before the first iteration |
| 4. Restoration | start of \(i\) \(\Rightarrow\) start of \(i{+}1\) |
| 5. Termination | the loop ends, and invariant gives result |
Here the invariant was the theorem with \(n\) replaced by \(i\). That is the easy case — often it has to say more than the theorem.
Proving correctness is only one use of invariants — they are also how you design a loop in the first place.
CPSC 221