Binary search boundaries
Find the first value at least x. The return value may equal n, indicating the insertion point after the final value.
| Candidate range | [lo, hi) | Index hi is exclusive |
| a[mid] < x | lo = mid + 1 | Discard the entire left prefix |
| a[mid] ≥ x | hi = mid | Keep mid as a potential boundary |
| Termination | lo == hi | The boundary has been located |
Python
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
else: hi = mid
return loC++
int lowerBound(const std::vector<int>& a, int x) {
int lo = 0, hi = (int)a.size();
while (lo < hi) {
int mid = lo + (hi-lo)/2;
if (a[mid] < x) lo = mid+1; else hi = mid;
}
return lo;
}Java
static int lowerBound(int[] a, int x) {
int lo = 0, hi = a.length;
while (lo < hi) {
int mid = lo + (hi-lo)/2;
if (a[mid] < x) lo = mid+1; else hi = mid;
}
return lo;
}