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

posted @ 2012-11-23 16:37  のんきネコ  阅读(1929)  评论(1编辑  收藏  举报