Proofs: Interpolation search
These are the human proofs of Interpolation search, at full length.
Interpolation search returns an index of x, or NIL, after at most n probes full
This proof shows: correctness, termination.
Let be numbers sorted in non-decreasing order, , and let be a number. We prove that INTERPOLATION-SEARCH stops after at most executions of line L4, and that it returns an index with when occurs in , and NIL otherwise.
Invariant. Before each test of line L2: , , and for every and every .
At the start and , and the statement about is empty.
The interpolation stays in the range. Suppose that the loop body runs. Then and . If line L3 does not return, then , so because the array is sorted and ; in particular . Let . Then , so , and since is an integer, . So line L4 gives , and is a valid read.
The step keeps the invariant. If , then for every , so no holds , and the new keeps the invariant. If , then for every , so the new keeps it. The bounds and are kept, because only grows and only shrinks.
Returns are correct. Line L7 returns only when . Line L3 returns only when , and then gives .
NIL is correct. Line L8 runs when the test of line L2 fails. If , the invariant says that no index with or holds , and these are all the indices. If and , then every in has ; with the invariant, is not in . The case is the same.
Termination. Each execution of line L4 is followed by a return or by a step that makes smaller by at least 1, since and either becomes or becomes . The value starts at and the loop body runs only while it is at least 1, so line L4 runs at most times.