Skip to main content

Iterative binary search

Those who have taken an algorithms course should have realized that, in the above case, we proved the correctness of the recursive implementation of binary search. Another implementation, using iterations, is used more often in practice. How can we prove correctness of such an implementation?

SEARCH(D,WD,W)

  1. 1,rn\ell \leftarrow 1, r\leftarrow n.
  2. While <r\ell < r
    1. m(+r)/2m \leftarrow \lceil (\ell+r)/2 \rceil
    2. Let WW' be the first word on the mm-th page.
    3. If WW should come before WW', then rm1r \leftarrow m-1; otherwise, m\ell \leftarrow m.
  3. Search for WW in the \ell-th page of DD line-by-line.
Lemma 2 (Loop invariant)

If WW is in DD, then it appears in one of the pages [,r][\ell, r].

This kind of statement is called loop invariant. It holds at the beginning of the loop, and if we can prove that it holds at the end of the loop, the correctness of the program would follow.

Proof:

Notice that the statement holds before the program enters the loop. We argue that if it holds before executing the instructions in the loop, then it holds after the execution. To see this, we can consider two cases: (a) If WW should come before WW', then it means that WW cannot be in page mm or after, so updating rm1r \leftarrow m-1 would maintain the validity of the statement. (b) Otherwise, we know that WW cannot appear in [1,m1][1,m-1], so we can update m\ell \leftarrow m, maintaining the validity of the statement.