Implement function countNumbers that accepts a sorted vector of unique integers and counts the number of vector elements that are less than the parameter lessThan.
For example, for vector v containing { 1, 3, 5, 7 }, SortedSearch::countNumbers(v, 4) should return 2 because there are two vector elements less than 4.
You do use recursion and do copy vectors, don't you?
Copies need time and memory.
The std has upper_bound, lower_bound, and equal_range.
They don't recurse or copy.
With vector's iterator's you can compute distance O(1).
1 2 3 4 5 6 7 8 9 10 11
#include <algorithm> // std::upper_bound
#include <vector> // std::vector
int main () {
std::vector<int> v { 1, 2, 3, 5, 7 };
auto foo = std::upper_bound( v.begin(), v.end(), 4 );
// foo points to the 5, to the foo[3]
auto distance = foo - v.begin();
// distance == 3 and there are 3 elements before foo[3]
return 0;
}
Do note that 5 is not less than 5. Therefore, std::upper_bound( v.begin(), v.end(), 5 ) - v.begin()
returns 4, not 3.
its sorted already. you can do a modified binary search to find the location in the array where the value to the left is < lessthan and the right is > lessthan. Take the right value's index. You have that many values less than it. I think this is the fastest way to get the answer. Of course you need to watch for edge cases etc. Which is pretty much what the above does, in English.