Data Structures & Algorithms / Module 10: Correctness and reviewing AI code
Topic 10.1
Loop invariants
One sentence that stays true on every pass, and how to use it to show a loop is right.
Watch: at every step, the promise "this is the biggest so far" is checked. If it breaks even once, the final answer must be wrong.
- moving now
- passed / marked
- finished / the result
Three questions
- Start: is the sentence true before the first pass?
- Every pass: if it's true at the start of a pass, is it still true at the end?
- End: when the loop stops, do the sentence and the stopping condition together give the answer you want?
It's like climbing a ladder: if you can get onto the first rung, and from any rung you can reach the next, then you can reach the top.
Example: finding the largest
Invariant: best is the largest of a[0] to a[i − 1]. Choose "best = 0" in the figure. The list is all negative, so even before the first pass the sentence is false: 0 isn't in the list. The loop still runs without errors and returns 0. The first question ("is it true at the start?") finds this bug right away, without having to guess an input that breaks it.
Code, for programmersThe invariant written as a comment
function max(a) {
if (a.length === 0) throw new Error("empty list");
let best = a[0];
// invariant: best is the largest of a[0..i-1]
for (let i = 1; i < a.length; i++) {
if (a[i] > best) best = a[i];
// still true: best is the largest of a[0..i]
}
// loop ended with i = a.length, so best is the largest of the whole list
return best;
}Invariants in algorithms you've seen
- Binary search: if the target exists, it's always between lo and hi.
- Insertion sort: the part a[0..i − 1] is always sorted.
- Two pointers: the right pair is never outside lo and hi.
- Dijkstra: every settled place has its true shortest distance.
Quiz
A loop invariant must be true…
max() starts with best = 0. Which input breaks it?
Insertion sort's invariant?
0 of 3 answered.