Why it matters

Even senior engineers get binary search wrong. Off-by-one errors on boundaries, wrong midpoint calculation, missing termination case. Getting the pattern right once and reusing it eliminates a class of bugs.

Advertisement

The architecture

The core loop maintains two pointers low and high defining the current search range. Each iteration computes mid, compares arr[mid] to target, and moves low or high.

Termination: when low > high (empty range), target isn't present.

Binary search stepCompare arr[mid]targetMove low or highshrink rangeReturn or continuefound or narrowEach step halves the range; log2(n) steps to find or eliminate
Binary search core loop.
Advertisement

How it works end to end

Correct midpoint: mid = low + (high - low) / 2 avoids integer overflow that low + high can cause on huge arrays.

Common bugs: infinite loop from mid computation that doesn't advance, off-by-one on inclusive vs exclusive bounds, wrong comparison direction.

Generalizations: binary search on answer (find the smallest x where some predicate is true), binary search over reals, parametric search.