BinarySearch how to find the value in the array between the two neighbors?
algorithm, arrays, binary-search, c#, find
Solution
When binary search does not find item in array, it returns a negative number which is the bitwise complement of the index of the first element that is larger than value. Here is the way you can use it to find range:
double[] spline_x = { 0D, 5D, 12D, 34D, 100D };
int i = Array.BinarySearch(spline_x, 25);
if (i >= 0)
{
// your number is in array
}
else
{
int indexOfNearest = ~i;
if (indexOfNearest == spline_x.Length)
{
// number is greater that last item
}
else if (indexOfNearest == 0)
{
// number is less than first item
}
else
{
// number is between (indexOfNearest - 1) and indexOfNearest
}
}
Problem
I have a sorted array double. The goal is to Find the index in the Array. Which contains the value of <= the value of search. For example the array contains numbers `{0, 5, 12, 34, 100}` with index range [0 .. 4]. Search for the value=25. And I want to get the index=2 (range of occurrences of between 12 and 34) I do not understand how in this case will run a binary search. ``` public class MyComparer : IComparer<double> { public int Compare(double x, double y) { //<-------- ??? } } public double[] spline_x; MyComparer cmpc = new MyComparer(); int i=Array.BinarySearch(spline_x, x, cmpc); ```