Algorithm Search⌘K

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 A[0…n−1]A[0 \ldots n-1] be sorted in non-decreasing order. We prove three facts about BINARY-SEARCH(A,x)(A, x).

Invariant. Before each test of line L2, these statements are true:

  1. 0≤lo≤hi≤n0 \le lo \le hi \le n.
  2. For each index i<loi < lo, A[i]<xA[i] < x.
  3. For each index i≥hii \ge hi, A[i]>xA[i] > x.

Start. Line L1 sets lo=0lo = 0 and hi=nhi = n. Statement 1 is true. Statements 2 and 3 are true because no index is less than 0 and no index is at least nn.

Step. Assume that the statements are true and that lo<hilo < hi. Line L3 sets mid=lo+⌊(hi−lo)/2⌋mid = lo + \lfloor (hi - lo)/2 \rfloor. Because hi−lo≥1hi - lo \ge 1, we have lo≤mid<hilo \le mid < hi.

  • If A[mid]<xA[mid] < x, line L5 sets lo′=mid+1lo' = mid + 1. For each ii with lo≤i≤midlo \le i \le mid, A[i]≤A[mid]<xA[i] \le A[mid] < x because AA is sorted. With statement 2 for the old lolo, each i<lo′i < lo' has A[i]<xA[i] < x. Also lo′≤hilo' \le hi because mid<himid < hi.
  • If A[mid]>xA[mid] > x, line L7 sets hi′=midhi' = mid. For each ii with mid≤i<himid \le i < hi, A[i]≥A[mid]>xA[i] \ge A[mid] > x. With statement 3 for the old hihi, each i≥hi′i \ge hi' has A[i]>xA[i] > x. Also lo≤hi′lo \le hi' because lo≤midlo \le mid.
  • Otherwise A[mid]=xA[mid] = x, and line L8 returns.

So the statements are true before the next test of line L2.

Termination. The value hi−lohi - lo is a non-negative integer by statement 1. In each step that does not return, it becomes smaller: in the first case hi−(mid+1)<hi−lohi - (mid + 1) < hi - lo because mid≥lomid \ge lo, and in the second case mid−lo<hi−lomid - lo < hi - lo because mid<himid < hi. A non-negative integer cannot become smaller for ever. So the loop stops.

Result. If line L8 returns midmid, then A[mid]=xA[mid] = x and 0≤mid<n0 \le mid < n, so the result is correct. If line L9 returns NIL, then lo≥hilo \ge hi, and by statement 1, lo=hilo = hi. By statements 2 and 3, each index ii has A[i]<xA[i] < x or A[i]>xA[i] > x. So no item of AA is equal to xx, and NIL is correct. ■\blacksquare

The number of steps. Let k=hi−lok = hi - lo before a step. The new size is ⌊(k−1)/2⌋\lfloor (k-1)/2 \rfloor or ⌈(k−1)/2⌉\lceil (k-1)/2 \rceil, and both are at most ⌊k/2⌋\lfloor k/2 \rfloor. Then after tt steps the size is at most ⌊n/2t⌋\lfloor n/2^t \rfloor, which is 0 when t=⌊lg⁡n⌋+1t = \lfloor \lg n \rfloor + 1. So the loop runs at most ⌊lg⁡n⌋+1\lfloor \lg n \rfloor + 1 times.

Back to Binary search