上次公司内部考试时考到了,但是没用过,考到了一大片。今天看书的时候又看到这个方法,于是稍微分析了一下。

    public  class Test
    {
        
        public static void Main(string[] args) 
        {
            int bookIndex;
            string[] book1 = { "book1", "book7", "book3" };
            bookIndex = Array.BinarySearch(book1,"book3");
            Console.WriteLine(bookIndex);

            Array.Sort(book1);
            bookIndex = Array.BinarySearch(book1, "book3");
            Console.WriteLine(bookIndex);
            Console.ReadLine();
        }
    }

以上代码,得到的结果是

-2

1

为什么同样是BirnarySearch,得到的结果不一样呢。

那是因为BirnarySearch用的是二分算法,在用BirnarySearch进行检索前,需要先对数组进行排序

 

然后又会有一个疑问,BirnarySearch实际上是来取对象在数组中的索引值。通常我们用的取索引值方法是IndexOf,那么BirnarySearchIndexOf又有什么区别呢。

BinarySearch是二进制搜索算法,复杂度为O(log n),效率更高,但需要先排序

IndexOf是线性搜索算法,复杂度为O(n),一般来说只适用于简单类型

相关文章:

  • 2021-08-30
  • 2022-12-23
  • 2022-12-23
  • 2021-07-15
  • 2022-12-23
  • 2021-03-31
  • 2021-09-29
  • 2021-06-16
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2021-08-14
  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
相关资源
相似解决方案