How binary search maintains a half-open range

Short answer: Binary search keeps the invariant that a missing or matching key, if it is present, lies in a half-open index range [lo, hi). The midpoint is lo + (hi−lo)//2, which does not overflow when lo and hi are large. The loop that sets hi = mid when a[mid] ≥ target returns the lower bound, the first index whose key is ≥ the target. The search is Θ(log n) comparisons on a sorted random-access array.


What the problem actually asks

The array is sorted nondecreasing, and any item can be read by index in constant time. Each comparison must throw away a portion of the remaining range, and the portion thrown away must be unable to hide the answer. The bug that ships is almost always the range convention: inclusive bounds, a midpoint of (lo+hi) that overflows, or a lower bound used as if it were an equality test.

Lower bound answers a different question than “is the key present.” It returns the first legal insertion index. Equality is that index, checked against n and against the key stored there.


What the algorithm guarantees

The loop invariant is: every index below lo holds a key < target, and every index at or above hi holds a key ≥ target. The range begins as [0, n). While lo < hi the midpoint lies strictly inside, because hi−lo ≥ 1 and the average rounds down. If a[mid] < target then the answer is in [mid+1, hi). Otherwise the answer is in [lo, mid). When lo = hi, lo is the first index with a key ≥ target, or n if every key is smaller. That is at most floor(log₂ n)+1 key comparisons.

The form lo+(hi−lo)//2 computes the same midpoint as (lo+hi)//2 when the sum does not overflow a fixed-width index, and it stays inside the index type when lo and hi themselves are legal. An upper bound, the first key strictly greater than target, is the same loop with the test a[mid] ≤ target advancing lo.


The working steps

  1. Set lo = 0 and hi = n on an array sorted nondecreasing.
  2. While lo < hi, set mid = lo + (hi−lo)//2.
  3. If a[mid] < target, set lo = mid+1. Otherwise set hi = mid.
  4. Return lo. This is the lower bound.
  5. The target is present only if lo < n and a[lo] equals the target. The last equal key ends at the upper bound, computed by advancing lo when a[mid] ≤ target.

The logarithmic bound needs random access and a sorted array. A linked list makes the midpoint expensive and the scan linear. An unsorted array makes the discarded half unsafe. A unimodal function, rather than a sorted array, is ternary search or a binary search on the slope.


Approaches that look simpler and fail

Approach Why it fails when the range invariant is broken
mid = (lo+hi)//2 in a fixed-width integer When lo and hi are both large, the sum overflows, mid becomes negative or small, and the range does not shrink toward the target.
Inclusive hi, with the loop condition lo ≤ hi, and hi = mid−1 on a miss This form can be written correctly and is easy to write one off. The half-open loop has a single shrinking rule and returns the insertion index with no second case.
Return mid as soon as a[mid] equals the target, from a lower-bound caller Equals may span a run. The first caller wanted the first equal, and an early return from a different loop answers an arbitrary equal.
Binary search a rotated or unsorted array with this loop The test a[mid] < target discards the left side only when the left side is known to be ≤ a[mid]. Without sorted order that is false.

Finding a boundary in a monotonic predicate, such as the first index where a property becomes true, is the same loop with the predicate in place of a[mid] < target. Searching an unordered array is linear search.


A working example

The Bash script and the Python script binary-search a half-open range. mid = lo + (hi-lo)//2, and a key that is not strictly smaller shrinks the high end. Both print the lower bound 1 of the value 2.

a=(1 2 2 3)
target=2
lo=0
hi=${#a[@]}
while (( lo < hi )); do
  mid=$(( lo + (hi - lo) / 2 ))
  if (( a[mid] < target )); then lo=$((mid+1))
  else hi=$mid; fi
done
echo "$lo"
a = [1, 2, 2, 3]
target = 2
lo, hi = 0, len(a)
while lo < hi:
    mid = lo + (hi - lo) // 2
    if a[mid] < target:
        lo = mid + 1
    else:
        hi = mid
assert lo == 1 and a[lo] == 2
print(lo)

Where it is used

git bisect is binary search over commits. bsearch, C++ lower_bound, and Java Arrays.binarySearch are the same half-open walk on a sorted array. A hash table is the replacement when the keys are not ordered and only equality matters.


When you can drop this algorithm

Drop binary search when the array is unsorted or is a linked list. Sort once if many queries will follow, or scan if they will not. Keep this half-open lower-bound loop whenever a sorted random-access array must yield a presence test or an insertion index in logarithmic comparisons.


Why this stays published

We publish this so a search for binary search returns the half-open lower-bound loop and the midpoint that does not add the endpoints. Binary search on a sorted array is the half-open loop that returns the first index whose key is at least the target, using a midpoint of lo plus half the width.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *