"Guess my number between 1 and a billion. If I tell you 'higher' or 'lower' each time, you'll nail it in about 30 guesses, not a billion. That's binary search, and that gap between 30 and a billion is the most important number in this quest."
The Algorithm
Binary search finds a target in a sorted array by repeatedly halving. Keep two pointers, low and high, bounding the region that could contain the target. Look at the mid element: if it's the target, done; if the target is larger, the answer must be in the upper half, so move low past mid; if smaller, move high below mid. Each comparison discards half the remaining region, so you reach the answer in log₂(n) steps. The 'sorted' requirement is the whole engine — it's what tells you which half to throw away.
Why log n Feels Like Magic
The power of halving is hard to overstate. A billion sorted items: linear search might check all billion; binary search checks about 30. Double the data to two billion, and binary search needs just one more step. That's the signature of O(log n) — adding a fixed amount of work each time you double the input. It's why sorted data plus binary search underpins databases, dictionaries, and version control's 'git bisect' (binary-searching commits to find the one that broke a test). When you can halve, intractable becomes instant.
The Off-By-One Minefield
Binary search is famously easy to get subtly wrong — a 2011 study found bugs in many textbook implementations. The danger spots: is the loop while low <= high or <? Do you update low = mid + 1 (skipping mid, since you already checked it) or low = mid (risking an infinite loop)? Compute mid = low + (high - low) // 2 rather than (low + high) // 2 to avoid integer overflow in languages that have it. These boundary details are exactly why the pros' advice is: understand binary search deeply, but use the library (Python's bisect) for real code, where the edge cases are already correct.
Pippa's Confession
bisect, because the off-by-one cases are a solved problem I don't need to re-solve (and re-bug) every time.