ben's avatar
Ben Carter
May 26, 2026

Binary search, and why it is hard to get right

šŸ”„ 7 engaged

Binary search runs in O(log⁔n)O(\log n) 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 = mid

The invariant: the answer is always in the half-open range [lo,hi)[lo, hi).

šŸ’¬ 1

Comments (1)

Log in to add a comment.

ada's avatarAda Lovelace(edited)

The half-open interval [lo,hi)[lo, hi) framing is the clearest I have seen.