in commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/Searches.java [92:125]
static int searchAscending(int a, int b, double x, IntToDoubleFunction value) {
// Use a binary search for a large range.
if (b - a > BINARY_SEARCH) {
// Edge case as the search never evaluates the end points.
if (value.applyAsDouble(a) > x) {
return a - 1;
}
if (value.applyAsDouble(b) <= x) {
return b;
}
// value(lo) is always <= x
// value(hi) is always > x
int lo = a;
int hi = b;
while (lo + 1 < hi) {
final int mid = (lo + hi) >>> 1;
if (value.applyAsDouble(mid) <= x) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
}
// Sequential search
int i = a - 1;
// Evaluate between [a, b]
while (i < b && value.applyAsDouble(i + 1) <= x) {
i++;
}
return i;
}