BinarySearch如何在两个邻居之间找到数组中的值?

Mix*_*xer 3 c# arrays algorithm find binary-search

我有一个排序数组double.目标是在Array中查找索引.其中包含<=搜索值的值.

例如,数组包含{0, 5, 12, 34, 100}索引范围为[0 .. 4]的数字.

搜索值= 25.我想得到指数= 2(出现的范围在12到34之间)

我不明白在这种情况下如何运行二进制搜索.

   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);
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 12

当二进制搜索不会在阵列发现项,它返回一个负数,其是比值大的第一个元素的索引的按位求补.以下是使用它来查找范围的方法:

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
    }     
}
Run Code Online (Sandbox Code Playgroud)