【问题标题】:BinarySearch how to find the value in the array between the two neighbors?BinarySearch 如何在两个邻居之间的数组中找到值?
【发布时间】:2013-02-02 13:31:41
【问题描述】:

我有一个排序数组 double。 目标是在数组中查找索引。 其中包含

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

搜索值=25。我想得到 index=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);

【问题讨论】:

    标签: c# arrays algorithm find binary-search


    【解决方案1】:

    当二分查找在数组中没有找到项时,它返回一个负数,它是第一个大于值的元素的索引的按位补码。以下是您可以使用它来查找范围的方法:

    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
        }     
    }
    

    【讨论】:

    • 谢谢。我有点简化: int i=Array.BinarySearch(spline_x, x);如果 (i= 0) { }
    • @Mixer 请记住,在减少 i 之后,您可以获得数组最后一项的索引的-1
    【解决方案2】:

    不熟悉 C#,但简单的二进制搜索可以解决问题,找到最后一个数字

    int find_last(int num, const vector<int>&v, size_t begin, size_t end) {
      if (begin >= end) {
        return -1;
      }
      size_t mid = (begin + end) / 2;
      if (v[mid] > num) {
        // [mid, end) is bigger than num, the boundary is in [begin, mid)
        return find_last(num, v, begin, mid);
      }
      // v[mid] is qualified as <= N, search [mid+1, end) for
      // approaching a better boundary if exists.
      size_t index = find_last(num, v, mid+1, end);
      return (index == -1 ? mid : index);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2022-12-01
      • 2012-01-20
      • 2020-03-05
      相关资源
      最近更新 更多