【问题标题】:Confused about BinarySearch in array对数组中的 BinarySearch 感到困惑
【发布时间】:2013-11-13 15:40:18
【问题描述】:

我对 BinarySearch 有点困惑,因为在很多情况下它不起作用。下面的程序显示 -5 和 -1。但它应该显示 1 和 3 对吗?

using System;

namespace Binary
{

    class Program
    {
        static void Main()
        {
            int[] array = { 12, 45, 23, 3, 67, 43 };
            int index1 = Array.BinarySearch<int>(array, 45);
            int index2 = Array.BinarySearch<int>(array, 3); 
            Console.WriteLine(index1);
            Console.WriteLine(index2);
        }
    }
}

【问题讨论】:

  • 想想二分查找是如何工作的。基本假设是“如果当前项目太小,则目标项目在其上方”。在您的数组中并非如此。

标签: c# binary-search


【解决方案1】:

要使 BinarySearch 起作用,数组需要排序。你的不是,所以它不能正常工作。

Quote: "Searches an entire one-dimensional sorted array for a specific element"

【讨论】:

    【解决方案2】:

    正如documentation 明确指出的那样,BinarySearch() 仅在数组已排序时才有意义:

    数组在调用这个方法之前必须先排序。

    【讨论】:

      【解决方案3】:

      二进制搜索仅适用于已排序的数组。由于搜索未找到您的值,因此返回负数。它们记录在这里:

      http://msdn.microsoft.com/en-us/library/2cy9f6wb(v=vs.110).aspx

      在搜索之前排序您的列表,它应该返回正确的值。如果您不想订购列表,请使用IndexOf 而不是BinarySearch

      【讨论】:

        【解决方案4】:

        直接从马嘴里:

        在整个一维排序的 System.Array 中搜索特定的 元素,使用由每个实现的 System.IComparable 接口 System.Array 的元素和指定的对象。

        您必须先对列表进行排序,BinarySearch 才能发挥作用。

        【讨论】:

          【解决方案5】:

          就像其他人说你的数组必须排序,所以只需在 int[] 数组之后输入 Array.Sort(array)... 像这样:

          static void Main(string[] args)
              {
                  int[] array = { 12, 45, 23, 3, 67, 43 };
                  Array.Sort(array);
                  int index1 = Array.BinarySearch<int>(array, 45);
                  int index2 = Array.BinarySearch<int>(array, 3);
                  Console.WriteLine(index1);
                  Console.WriteLine(index2);
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-31
            • 2016-02-13
            • 2021-11-28
            • 2019-09-13
            • 2012-07-22
            相关资源
            最近更新 更多