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()
- .
- While
- Let be the first word on the -th page.
- If should come before , then ; otherwise, .
- Search for in the -th page of line-by-line.
If is in , then it appears in one of the pages .
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.
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 should come before , then it means that cannot be in page or after, so updating would maintain the validity of the statement. (b) Otherwise, we know that cannot appear in , so we can update , maintaining the validity of the statement.