In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater or less than
My following implementation uses condition bottom <= top which is different from the answer of @templatetypedef.
int FirstElementGreaterThan(int n, const vector& values) {
int B = 0, T = values.size() - 1, M = 0;
while (B <= T) { // B strictly increases, T strictly decreases
M = B + (T - B) / 2;
if (values[M] <= n) { // all values at or before M are not the target
B = M + 1;
} else {
T = M - 1;// search for other elements before M
}
}
return T + 1;
}