Loop Invariants and Binary Search

Prove a boundary-search algorithm by maintaining a half-open interval and separating correctness from termination.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Describe the remaining candidates
  2. Check the two updates and the exit

Describe the remaining candidates

Let \(a\) be a nondecreasing array of length \(n\). To find the first index with \(a_i\ge x\), maintain boundaries \(l,r\) so every index below \(l\) is too small and every index at or above \(r\), within the array, is large enough. The candidate boundary lies in the inclusive range \([l,r]\), even though the unclassified array elements occupy \([l,r)\). Start with \(l=0,r=n\). Both assertions then hold vacuously.

Check the two updates and the exit

For midpoint \(m=l+\lfloor(r-l)/2\rfloor\), set \(l=m+1\) if \(a_m<x\). Monotonicity discards all earlier indices. Otherwise set \(r=m\), retaining the possibility that \(m\) is the first match. The width strictly decreases in either branch, as in termination arguments. At equality the two excluded regions meet and determine the answer. For \(a=(1,4,4,7)\) and \(x=4\), the result is \(1\). The same reasoning works when the result is the past-the-end index \(n\). Hoare triples express the invariant as a formal assertion.[1][2]

References

  1. Jeff Erickson, Algorithms ↩
  2. Eric Lehman, F. Thomson Leighton and Albert R. Meyer, Mathematics for Computer Science ↩