Q&A-15How would you explain the comparison function contract without using the usual slogan?
Answer
The contract has three clauses, and binary search needs all three: the comparator must be total (every pair yields a consistent ordering. NaN breaks this because every NaN < x and x < NaN is false, so the ordering is inconsistent rather than absent), transitive (a<b and b<c implies a<c), and consistent with the order the array was actually sorted with. The last clause is the one people forget: the comparator isn't just a function you hand to bisect, it's a claim about how the data underneath was arranged. Violate any clause and you don't get an exception: you get a confident wrong index, because the elimination step is still doing exactly what it was told to do.
Why it fails silently. Each probe compares once and throws away half the array. If the comparator says arr[mid] < target, the answer must be to the right: that inference only holds under the contract. With a non-transitive comparator (say, a fuzzy string match that's pairwise but not ordered), the true target can sit in the half you just discarded, and nothing downstream will ever look there. O(log n) probes, each one locally reasonable, globally wrong. That's why the failure survives casual testing: a 10-element list with a linear-scan sanity check hides it, and it only shows up at the scale where binary search was worth using in the first place.
The classic bug, concretely:
import bisect
people = sorted([("ana", 34), ("bo", 19), ("cy", 30)], key=lambda p: p[1])
# sorted by age: [("bo", 19), ("cy", 30), ("ana", 34)]
names = [p[0] for p in people] # ["bo", "cy", "ana"] — not alphabetical
bisect.bisect_left(names, "ana") # returns 0Trace: lo=0, hi=3, mid=1, "cy" < "ana" is false so hi=1; mid=0, "bo" < "ana" is false so hi=0; loop ends, returns 0. The correct answer is index 2, that's where "ana" sits, and a linear scan would find it. No exception is raised at any step; the search just eliminated the half containing the answer on its first probe. Python 3.10+ closes the drift risk: bisect.bisect_left(people, 30, key=lambda p: p[1]) keeps the sort key and the search key in one expression, so they can't diverge across a refactor. Before 3.10, the idiom is to extract the key list once and reuse it for both sort and search.
Trade-offs worth naming: if the data is small, under a few hundred elements, a linear scan is O(n) but immune to comparator mismatch, and the constant factors make it just as fast; binary search earns its complexity only when n is large enough that O(n) hurts or the array is searched many times per sort. If you can't guarantee the sort order (data arriving from another service, mutated since sorting), either re-sort with the same comparator or fall back to a scan: don't binary search over an unverified invariant.
How you'd catch it: a property test asserting bisect_left(arr, x) returns an index where everything left of it compares less and everything from it compares greater-or-equal, run against the real comparator on real data. That check fails immediately for a non-transitive or mismatched comparator, and it's cheap enough to run in CI.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.