Skip to content

Lesson 3 of 14 · 18m

Binary Search: The Algorithm That Still Breaks

~90% of professionals ship it buggy per Bentley's courses, and Java's `Arrays.binarySearch` carried an overflow for nine years — the invariant is the whole game.

git bisect exists because finding the commit that broke the build among 1,024 candidates takes about 10 checkouts, not 1,024. Mark one good, one bad, and git walks the middle until only the culprit remains. That's binary search over history — and it's the same algorithm running inside bisect.bisect_left, std::lower_bound, and Go's sort.Search.

It's also the algorithm professionals get wrong. Jon Bentley assigned it in courses at Bell Labs and IBM and reported that roughly 90% of the programmers produced a buggy version. The receipts: java.util.Arrays.binarySearch carried an integer-overflow bug for about nine years — mid = (low + high) / 2 wraps negative when low + high exceeds INT_MAX — until Josh Bloch published "Extra, Extra: Nearly All Binary Searches and Mergesorts are Broken" in June 2006. The fix is mid = low + (high - low) / 2 or Java's unsigned shift (low + high) >>> 1. Python's ints don't overflow, but the habit transfers — and the deeper lesson isn't arithmetic, it's that the boundaries are where binary search lives and dies.

The invariant is the whole game

Binary search bugs are boundary bugs, and they come from an unstated interval. Pick one and write it down:

  • lo, hi = 0, len(a) searches the half-open range [lo, hi) — while lo < hi, and hi = mid on the high side. This is what bisect uses.
  • lo, hi = 0, len(a) - 1 searches the closed range [lo, hi] — while lo <= hi, and hi = mid - 1.

Mix them — lo < hi with hi = mid - 1 — and you either skip an element or loop forever. There is no third option; there are only programmers who didn't decide.

from bisect import bisect_left, bisect_right
i = bisect_left(a, x)   # first index where a[i] >= x; == len(a) if absent
j = bisect_right(a, x)  # first index where a[i] >  x
count_of_x = j - i      # works because equal keys are contiguous

bisect_left returns the insertion point whether or not x exists — check i < len(a) and a[i] == x before claiming a match. bisect.insort does the O(log n) find then the O(n) insert — maintaining a sorted list is find-cheap, insert-expensive, which is why sortedcontainers.SortedList exists for write-heavy workloads.

Searching the answer, not the array

The productive form binary searches a predicate, not data. "What's the smallest ship capacity that delivers all packages in D days" — check(cap) is monotone (bigger capacity never ships slower), so binary search the capacity space between max(weights) and sum(weights). "First bad version" is bisect_left over is_bad(v). Any monotone yes/no function over an integer range — threshold, cutoff, earliest timestamp — is a search space, and each check call replaces a sorted array's element read.

The same move works on files: a 10GB sorted log on disk can be searched by seeking to byte offsets and scanning to the next newline — bisect logic, just with f.seek instead of a[mid].

What to actually do

State [lo, hi) or [lo, hi] before writing the loop. Use bisect in Python — it's C-accelerated and already correct. Test the degenerate cases: empty range, one element, target below everything, above everything. And when the "array" is really a condition — versions, capacities, thresholds — write check(x), confirm it's monotone, and binary search the answer.

Field notes

  • bisect_left vs bisect_right differ only on equal elements — for "first ≥ x" use _left, for "first > x" use _right; j - i counts occurrences for free.
  • A rotated sorted array still binary-searches — one half is always sorted; check which half contains the target and descend there.
  • bisect returns len(a) when x exceeds everything — index bounds are your check, not the function's error.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.