Precisely stated variant
Lower-bound search: return the first index
p such that A[p] ≥ x. If no value
equals x, p is the insertion position.
lowerBound(x):
L = 0; R = n
while L < R:
m = L + floor((R - L) / 2)
if A[m] < x:
L = m + 1
else:
R = m
return L
Interval invariant: every index below L has a value
< x, and every index at or above R has a value ≥ x. Therefore the
lower bound remains inside the half-open interval [L, R).
Why R = m is safe: when A[m] = x, index m remains a
valid candidate. Using R = m − 1 would incorrectly discard it and
could skip the first equal-valued index.
For duplicate handling, after finding p = lowerBound(x), the same
routine at x + 1 gives q. All equal-valued candidate indices are
exactly the half-open range [p, q).