Binary Search on Sorted Data
Discard half the remaining sorted search space after each comparison.
Input is sorted, or a condition changes monotonically from false to true or true to false.
How to approach it
Use mid = left + floor((right - left) / 2). Decide carefully whether the active interval is closed or half-open, and return the boundary the invariant describes.
Duplicates and boundary answers require explicit handling; a basic exact-match search may not find the first or last occurrence.
Practice question
In [2, 4, 4, 4, 7, 9], find the first index containing 4.
sorted = [2, 4, 4, 4, 7, 9], target = 4Give your answer before revealing the explanation.Show a hint
Store the match as a candidate, then move the right boundary leftward.
Show an answer
Index 1 (zero-based). Continue searching left after finding a match.
Binary Search on Sorted Data at work
A library catalog lists book IDs in sorted order. There are 1,024 entries. About how many midpoint checks are needed to find one ID, or establish it is absent?
Show one possible approach
At most about 11 checks, since each check halves the remaining entries and 2¹⁰ = 1,024 (with one final boundary check depending on the implementation).
Practice next
Use these problem IDs to find additional practice for this pattern: