The algorithm returns the first index whose value is at least
target.- The input array
amust be sorted in nondecreasing order. - If no value qualifies, the result is
len(a). - Repeated values are allowed.
The search maintains a half-open interval
[lo, hi).- Every index before
locontains a value smaller thantarget. - Every index at or after
hicontains a value at leasttarget. - Either region may initially be empty.
Initialize
lo = 0andhi = len(a).- The invariant [2] holds because both excluded regions are empty.
While
lo < hi, inspectmid = lo + (hi - lo) / 2using integer division.- The index
midlies inside the current interval. If
a[mid] < target, setlo = mid + 1.Sorted order implies every index through
midis too small.- For any index
j ≤ mid, sorted order givesa[j] ≤ a[mid]. - Combining that inequality with
a[mid] < targetgivesa[j] < target.
- Excluding those indices preserves the invariant [2].
Otherwise, set
hi = mid.- Sorted order implies every index from
midonward qualifies. - Keeping
midas the boundary preserves the possibility that it is the first qualifying index. - Setting
hi = mid - 1would use the wrong interval convention.
The loop terminates because each iteration strictly reduces
hi - lo.- The lower-bound update [4.2] raises
loby at least one. - The upper-bound update [4.3] lowers
hiby at least one. - The interval length remains a nonnegative integer.
Return
lowhenlo == hi.- The invariant says that all earlier indices are too small.
- The invariant says that this index qualifies whenever it is inside the array.
- Together these statements establish the contract [1].
Searching for
4in[1, 4, 4, 9]returns1.- Starting at
[0, 4)inspects index2and moveshito2. - Searching
[0, 2)inspects index1and moveshito1. - Searching
[0, 1)inspects index0and movesloto1. - The termination condition [5] now holds.