Lecture Notes — Lecture 21: Binary Search Everywhere

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

Binary search is a precondition turned into an algorithm: if the data is sorted (or the answer sits in a monotone yes/no landscape), every probe of the middle discards half the remaining space. Twenty probes cover a million items. The discipline is the invariant - 'the target, if present, lies in lo..hi' - maintained by every branch. The variant that unlocks the block is searching on the answer: 'smallest capacity that works' is findable by binary search whenever feasibility is monotone (works, works... fails, fails). Book allocation and first-bad-commit are that pattern in disguise: the predicate does the work, the halving does the speed. Common ground: every binary-search bug is an off-by-one or a broken invariant, which is why we write the invariant as a comment and test on 0, 1, and 2 elements. If you can state 'yes for small, no for large' (or vice versa), you can binary search it.

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. Sorted data (or a monotone yes/no landscape) converts scanning into halving.
  2. Write the invariant first: 'the target lies in lo..hi' survives every branch.
  3. Every binary-search bug is an off-by-one or a broken invariant - test on 0, 1, 2 elements.
  4. The predicate variant searches answers, not arrays: smallest feasible cap, first bad commit.
  5. O(log n): a million items in twenty probes - preconditions have this price tag.

Practice questions

Where this leads

Next lecture: Recursion II: Divide and Conquer. The quiz below checks this lecture's essentials before we build on them.