Proofs: Boyer-Moore-Horspool algorithm
These are the human proofs of Boyer-Moore-Horspool algorithm, at full length.
Horspool outputs exactly the valid shifts full
This proof shows: correctness, termination.
Claim. For a text and a pattern , HORSPOOL stops and outputs exactly the shifts , , with , in increasing order.
For , line L2 outputs every shift, which is correct. Let . After lines L3 and L4, for every character ,
because line L4 visits in increasing order and the last write for is its largest , which gives the smallest value . In particular .
Lemma (safe shift). Let and . No shift with is valid.
Proof. Let with be valid. The text position lies in the window at , because . It is aligned with the pattern position , and . Validity gives , so belongs to the set in the definition of , and , a contradiction.
Theorem. The claim holds.
Proof. Invariant at line L6: the output is the increasing list of the valid shifts smaller than . It holds for . In an iteration with , lines L7 and L8 end with exactly when for all , so line L9 outputs exactly when it is valid, after all smaller outputs. By the lemma, no valid shift lies strictly between and the new value , so the invariant holds again. Each iteration increases by at least 1, so the loop stops after at most iterations, with ; then all valid shifts are smaller than and have been output.