zoukankan      html  css  js  c++  java
  • C# BinarySearch

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

        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),一般来说只适用于简单类型

  • 相关阅读:
    [IOI1994][USACO1.5]数字三角形 Number Triangles
    和为给定数
    小凯的疑惑
    棋盘
    【2020NOI.AC省选模拟#2】C. 送分题
    【NOI OL #2】涂色游戏
    【NOI OL #3】小结
    【NOI OL #1】最小环
    【NOI OL #1】冒泡排序
    【NOI OL #1】序列
  • 原文地址:https://www.cnblogs.com/nonkicat/p/2784696.html
Copyright © 2011-2022 走看看