Suppose I have a sorted array of integers int[]
, and I want to search the closest smaller value to some input number.
for example if the array contains (1) , (23), (57) , (59), (120) and the input is 109, the output should be 59.
I am just trying to see suggestions and compare to the approaches I already have.
I'd go for a linq solution (updated: to add a little more code to stop from being similar to fear's similar solution):
using Linq:
Maybe not the fastest but probably the easiest to implement. Also doesn't rely on the array being sorted, as binary search does.
Note that the call to
Max
will throw an exception if theWhere
filter results in no elements, so you might want to check that if it's a possibility.just to extrapolate on the other LINQ solutions this extension method will return -1 if no objects fits the filter and expects that the list is all positive integers
usage would look like this:
Use Array.BinarySearch. If the input is in the list, it will return the index, and if not then it will return the complement of the index of the first larger value. You just invert the result and subtract one to get the index of the closest smaller value.
Note that if you have an input smaller than the smallest element, you don't have a well-defined answer.