Let’s say I have sorted precomputed floats:
1, 3, 10, 29
Let’s say my “input” is 7.3. I want my program to return 3 and 10 since they are the numbers in my array that are before and after 7.3.
What is the fastest method to do it? I’m assuming you can do it in log(n) time using binary search but is it possible to do it in constant time?
You can’t do it in constant time unless you limit the input to a small number of predetermined values. Just use binary search.
The C++ function for binary search is
lower_bound. (There are others too but you wantlower_bound.)