Binary Search (done right)

Binary search is famous for its simplicity and for how often it is implemented incorrectly. A correct implementation follows from a precise specification, clear boundary semantics, explicit loop invariants, and a proof of termination. Special care is required for midpoint computation in fixed-width integer arithmetic to avoid overflow and subtle out-of-bounds failures.