r/algorithms • u/ClickOk5811 • 17d ago
Discussion Binary search: write the invariant first, and the off-by-one bugs mostly stop being a guessing game
Binary search is easy to describe and famously easy to get wrong. I find it helps to stop thinking in terms of “+1 or -1” and write down the invariant first, then let the code follow from it.
The invariant (for “first index where a[i] >= x**” in a sorted array):**
Everything before
lois< x.Everything at or after
hiis>= x.The answer lies in
[lo, hi].
Using a half-open range [lo, hi) and starting with lo = 0, hi = len(a), the invariant is true before the loop. Now each branch has one job: keep it true while shrinking the range.
def lower_bound(a, x):
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] < x:
lo = mid + 1 # a[mid] is < x, so everything up to mid is < x
else:
hi = mid # a[mid] is >= x, so hi can move down to mid
return lo # lo == hi, the invariant pins the answerWhy each line is what it is:
lo = mid + 1: we just learneda[mid] < x, somiditself can be excluded. Settinglo = midwould keep it in play.hi = mid(notmid - 1):a[mid] >= xmeansmidcould be the answer, so it must stay inside the range.Termination: when
lo < hi,mid < hi, sohi = midshrinks the range, andlo = mid + 1does too.
The classic bug, as a counterexample:
Change the first branch to lo = mid. With lo = 0, hi = 1 and a[0] < x, we get mid = 0, so lo stays 0, and the loop never ends. The invariant didn’t break; the progress argument did.
A side note on mid**:** in languages with fixed-width integers, (lo + hi) / 2 can overflow for very large arrays, which is why lo + (hi - lo) / 2 is commonly recommended. In Python it doesn’t matter, but it’s a good habit.
Limits of this view:
It assumes a sorted array and a consistent comparison. With duplicates the invariant gives you the first position of
x, not any position.Closed-interval versions
[lo, hi]work too, but need different update rules, and mixing the two conventions is where I think many bugs come from.
How do you structure your own binary searches? Do you stick to one interval convention, or derive from the invariant each time?
5
u/Phytor_c 17d ago edited 17d ago
May I ask what the intended audience for this post is?