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)
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.
int[] arr = { 1, 23, 57, 59, 120 };
int index = Array.BinarySearch(arr, 109);
if (index < 0)
{
index = ~index - 1;
}
if (index >= 0)
{
var result = arr[index];
}
Note that if you have an input smaller than the smallest element, you don't have a well-defined answer.