Proofs: Linear search
These are the human proofs of Linear search, at full length.
Linear search returns the first index of x, or NIL when x is not in A full
This proof shows: correctness, termination.
Let be an array with and let be a key. We prove that LINEAR-SEARCH stops, and that it returns the smallest index with , or NIL when there is no such index.
Invariant. Before the pass of the loop of line L1 with index , and also when the loop ends with , this statement holds:
Start. The first pass has . The range is empty, and , so holds. If the loop does no pass, and is the statement at the end.
Step. Assume and that the pass with index runs, so . Line L2 tests . If the test is true, the algorithm returns and the loop has no next pass. If the test is false, then . With , for each , and . So holds before the next pass, or at the end of the loop when .
Termination. The index starts at 0 and grows by exactly 1 in each pass that does not return. The loop has no pass with . So it runs at most passes, and the algorithm stops after at most key tests.
Result. There are two ways to stop.
- Line L2 returns . Then and , so is an index of . By , no index has . So is the smallest index of .
- Line L3 returns NIL. The loop ended after the pass with or, when , without a pass. In both cases holds: for each with . So is not in and NIL is correct.
The number of tests. If first occurs at index , the algorithm makes exactly key tests: the passes fail by the minimality of , and the pass succeeds. If is absent, it makes exactly key tests. These counts give the best, worst and average cases on the page.