Algorithm Search⌘K

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 A[0…n−1]A[0 \ldots n-1] be numbers sorted in non-decreasing order, n≥0n \ge 0, and let xx be a number. We prove that INTERPOLATION-SEARCH(A,x)(A, x) stops after at most nn executions of line L4, and that it returns an index ii with A[i]=xA[i] = x when xx occurs in AA, and NIL otherwise.

Invariant. Before each test of line L2: 0≤lo0 \le lo, hi≤n−1hi \le n - 1, and A[j]≠xA[j] \ne x for every j<loj < lo and every j>hij > hi.

At the start lo=0lo = 0 and hi=n−1hi = n - 1, and the statement about jj is empty.

The interpolation stays in the range. Suppose that the loop body runs. Then lo≤hilo \le hi and A[lo]≤x≤A[hi]A[lo] \le x \le A[hi]. If line L3 does not return, then A[lo]≠A[hi]A[lo] \ne A[hi], so A[lo]<A[hi]A[lo] < A[hi] because the array is sorted and lo≤hilo \le hi; in particular lo<hilo < hi. Let t=(x−A[lo])/(A[hi]−A[lo])t = (x - A[lo])/(A[hi] - A[lo]). Then 0≤t≤10 \le t \le 1, so 0≤t⋅(hi−lo)≤hi−lo0 \le t \cdot (hi - lo) \le hi - lo, and since hi−lohi - lo is an integer, 0≤⌊t(hi−lo)⌋≤hi−lo0 \le \lfloor t (hi - lo) \rfloor \le hi - lo. So line L4 gives lo≤pos≤hilo \le pos \le hi, and A[pos]A[pos] is a valid read.

The step keeps the invariant. If A[pos]<xA[pos] < x, then A[j]≤A[pos]<xA[j] \le A[pos] < x for every j≤posj \le pos, so no j<pos+1j < pos + 1 holds xx, and the new lo=pos+1lo = pos + 1 keeps the invariant. If A[pos]>xA[pos] > x, then A[j]≥A[pos]>xA[j] \ge A[pos] > x for every j≥posj \ge pos, so the new hi=pos−1hi = pos - 1 keeps it. The bounds 0≤lo0 \le lo and hi≤n−1hi \le n - 1 are kept, because lolo only grows and hihi only shrinks.

Returns are correct. Line L7 returns pospos only when A[pos]=xA[pos] = x. Line L3 returns lolo only when A[lo]=A[hi]A[lo] = A[hi], and then A[lo]≤x≤A[hi]=A[lo]A[lo] \le x \le A[hi] = A[lo] gives A[lo]=xA[lo] = x.

NIL is correct. Line L8 runs when the test of line L2 fails. If lo>hilo > hi, the invariant says that no index jj with 0≤j<lo0 \le j < lo or hi<j≤n−1hi < j \le n - 1 holds xx, and these are all the indices. If lo≤hilo \le hi and x<A[lo]x < A[lo], then every jj in [lo,hi][lo, hi] has A[j]≥A[lo]>xA[j] \ge A[lo] > x; with the invariant, xx is not in AA. The case x>A[hi]x > A[hi] is the same.

Termination. Each execution of line L4 is followed by a return or by a step that makes hi−lohi - lo smaller by at least 1, since lo≤pos≤hilo \le pos \le hi and either lolo becomes pos+1≥lo+1pos + 1 \ge lo + 1 or hihi becomes pos−1≤hi−1pos - 1 \le hi - 1. The value hi−lo+1hi - lo + 1 starts at nn and the loop body runs only while it is at least 1, so line L4 runs at most nn times. ■\blacksquare

Back to Interpolation search