Proofs: Boyer-Moore algorithm
These are the human proofs of Boyer-Moore algorithm, at full length.
Boyer-Moore outputs exactly the valid shifts full
This proof shows: correctness, termination.
Claim. For a text and a pattern , BOYER-MOORE stops and outputs exactly the shifts , , with , in increasing order.
We take as given the two tables: is the largest with , or ; and , for , is the smallest such that (G1) for all with and , and (G2) or . That lines L13 to L23 compute these values is the procedure described on the page of the good-suffix rule. For , line L2 outputs every shift, which is correct, so let .
Lemma 1 (the period). is the smallest period of , the smallest with for all .
Proof. For , (G2) always holds because , and (G1) asks for , which is the same as since .
Lemma 2 (safe shifts). Let be a shift tested by the loop of line L5, and let be the amount added to by line L11 or L12. Then , and no shift with is valid.
Proof. If the window matched (line L11), . A valid shift with would give for all , since both at and at equal the text there; so would be a period smaller than , a contradiction.
Otherwise, lines L7 and L8 stopped at with for and , and . Let be valid with , so for , and .
- If , then (G1) or (G2) fails for . For with , the text position lies in both windows, so : (G1) holds. So (G2) fails: and . But the text position is in the window at , so , a contradiction.
- If , then , so and . That is an occurrence of at the position , which contradicts the definition of .
In both cases is not valid.
Theorem. The claim holds.
Proof. We show the invariant: at line L5, the output is the increasing list of the valid shifts smaller than . It holds for . In one iteration, the window at is tested by lines L6 to L8, which stop with exactly when for all ; then is output, and it is larger than every earlier output. By Lemma 2, no shift strictly between and is valid, so the invariant holds for . Each iteration increases by at least 1, so the loop stops after at most iterations, with ; the inner loop runs at most times. At that point every valid shift, being at most , is smaller than , so the output is complete.