Ben Carter
May 26, 2026
Binary search, and why it is hard to get right
š„ 7 engaged
Binary search runs in time, but the off-by-one bugs are famous.
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target: lo = mid + 1
else: hi = midThe invariant: the answer is always in the half-open range .

Comments (1)
Log in to add a comment.
The half-open interval [lo,hi) framing is the clearest I have seen.