Proofs: Naive string matching
These are the human proofs of Naive string matching, at full length.
Naive string matching outputs exactly the valid shifts full
This proof shows: correctness, termination.
Claim. For a text and a pattern with , NAIVE-STRING-MATCHING stops, and it outputs exactly the shifts with and , each one time, in increasing order.
Setup. Fix one iteration of line L2, with shift , . So , and each index with is a valid index of .
Lemma (inner loop). Each time line L4 tests its condition, the invariant
(I) and for each
is true.
Proof. 1. Initialization. Line L3 sets . Then because , and the second part is about no index, so it is true.
-
Maintenance. Assume (I) and that the test of line L4 is true. Then and . Line L5 sets . The equality for holds by the test, and the equalities for hold by (I). So (I) holds for .
-
Termination. Each pass of the loop increases by exactly 1, and (I) gives . So the loop makes at most passes and stops.
Lemma (one shift). Line L6 outputs if and only if .
Proof. When the loop of line L4 stops, (I) holds and the test is false, so or with .
- If , then (I) gives for each , so is a valid shift, and line L6 outputs it.
- If , then , so is not a valid shift, and line L6 outputs nothing.
The test is evaluated first, so the loop never reads or .
Theorem. The claim holds.
Proof. If , then , line L2 makes no iteration, and the output is empty. This is correct, because no satisfies . Otherwise, line L2 runs the body for , each value one time and in increasing order, and each body stops by the first lemma. By the second lemma, the body for outputs exactly when is a valid shift. So the output is the list of valid shifts in increasing order, and the algorithm stops after iterations of line L2. If , the loop of line L4 stops at once with , so each from to is output, as the definition requires.