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
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
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 libraryQuick 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?
Related Concepts
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.