Proofs: Binary search
These are the human proofs of Binary search, at full length.
Binary search returns an index of x, or NIL when x is not in A full
This proof shows: correctness, termination.
Let be sorted in non-decreasing order. We prove three facts about BINARY-SEARCH.
Invariant. Before each test of line L2, these statements are true:
- .
- For each index , .
- For each index , .
Start. Line L1 sets and . Statement 1 is true. Statements 2 and 3 are true because no index is less than 0 and no index is at least .
Step. Assume that the statements are true and that . Line L3 sets . Because , we have .
- If , line L5 sets . For each with , because is sorted. With statement 2 for the old , each has . Also because .
- If , line L7 sets . For each with , . With statement 3 for the old , each has . Also because .
- Otherwise , and line L8 returns.
So the statements are true before the next test of line L2.
Termination. The value is a non-negative integer by statement 1. In each step that does not return, it becomes smaller: in the first case because , and in the second case because . A non-negative integer cannot become smaller for ever. So the loop stops.
Result. If line L8 returns , then and , so the result is correct. If line L9 returns NIL, then , and by statement 1, . By statements 2 and 3, each index has or . So no item of is equal to , and NIL is correct.
The number of steps. Let before a step. The new size is or , and both are at most . Then after steps the size is at most , which is 0 when . So the loop runs at most times.