All Concept Bites
23 views
Programming Languagesintermediate

Binary Search: Why the Boundary Breaks Your Code

The bug is almost never the idea — it's which end of the range you forgot to move.

Reviewed by Abhijith N M · 24 October 2026 · Editorial standards

The Simple VersionNo jargon

Binary search keeps a range of the list that might still contain your target. Call it the live range. Each step, you look at the middle element and throw away half the range. The algorithm is simple. The bookkeeping is not. Take a sorted list of ten numbers and search for the value at index 0. You set low = 0 and high = 9. The middle is index 4. Too big, so the target must be left of 4. Now: is the new live range 0..3, or 0..4? If you write high = mid instead of high = mid - 1, index 4 stays live forever. When low and high both land on 4, the middle is 4 again, and the loop never ends. If you write high = mid - 1 but your loop condition is low < high instead of low <= high, you can exit one step early and silently return "not found" for a value that is sitting right there. Neither bug crashes. One hangs, one lies. That is why binary search is hard: the concept fits in a sentence, but the correctness lives in two comparisons that must agree with each other. The fix is to write down the invariant before the code. Say out loud: "the answer, if it exists, is always inside low..high inclusive." Then every line you write must keep that sentence true. If you shrink to mid - 1, the invariant holds. If you shrink to mid, it does not, and you have just written an infinite loop. In Python, the bisect module already encodes this correctly. Reach for it unless you have a reason not to.

Binary Search: Why the Boundary Breaks Your Code — Visual Breakdown

Click any step below to inspect
low=0, high=n-1 (inclusive)
mid = (low + high) // 2
compare a[mid] to target
high = mid-1 or low = mid+1
loop while low <= high
Sequence of Events
Why It Matters in Production
Binary search shows up in interviews, in contest problems, and inside real code that looks up ranges, timestamps and sorted keys. The failure mode is what makes it costly: a wrong boundary does not raise an exception, it either loops forever or returns a wrong answer that passes casual testing. Small inputs often hide the bug because the loop exits before the bad state is reached. Writing the invariant down first, and testing against the smallest and largest elements, catches most of these. For production Python, bisect already implements the boundary logic correctly, so the practical rule is to use it unless you have a specific reason to hand-roll the loop.
Implementation & Syntax
🐍Python
import bisect

def search(a, target):
    low, high = 0, len(a) - 1   # invariant: answer, if present, is in a[low:high+1]
    while low <= high:
        mid = (low + high) // 2
        if a[mid] == target:
            return mid
        elif a[mid] < target:
            low = mid + 1        # mid is ruled out
        else:
            high = mid - 1       # mid is ruled out
    return -1

nums = [1, 3, 5, 7, 9]
print(search(nums, 1))              # 0
print(bisect.bisect_left(nums, 7))  # 3, from the standard library

Quick Concept Check

Test your understanding in 15 seconds

You write a binary search with `high = len(a) - 1` and the loop condition `while low <= high`. Inside, when `a[mid] > target`, which assignment keeps the invariant intact?

Bite Progression30 / 36

Related Concepts

Complementary topics

Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.