Let's say I have an array of lots of values (C++ syntax, sorry):
vector<double> x(100000);
This array is sorted such that x[n] > x[n-1]
.
I would like a function to retrieve an array of all values in the range [a, b] (that's inclusive). Some interface like:
void subarray(const double a, const double b, vector<double> &sub) {
...
}
When this function completes, sub
will contain the n
values that fell in the range [a, b].
Of course a linear search is easy:
void subarray(const double a, const double b, vector<double> &sub) {
for (size_t i = 0; i < data.size(); i++) {
if (a <= data[i] && data[i] <= b) {
sub.push_back(data[i]);
}
}
}
However, because data
is sorted, I should be able to do this much faster using a binary search. Who wants to take a stab at it? Any language is permitted!