zoukankan      html  css  js  c++  java
  • C#中List<T>的BinarySearch方法

      利用List或者数组存储数据,希望以此改善你的程序,可以对List或者数组的BinarySearch方法进行评估。如果是一个可变数量的元素集合,Binary搜索是针对集合中的值进行排序的一种“令人吃惊的”算法,其算法复杂度为O(log n),与C#中其它排序方法相比,它具备更高的效率。

      示例:

      下面是一个对List类型使用BinarySearch方法的示例。你必须为List中所使用的类型提供一个值,这样该方法才能通过编译。程序中通常使用字符串,这里也就使用string类型。

    BinarySearch方法示例代码:

     1 using System;
    2 using System.Collections.Generic;
    3
    4 class Program
    5 {
    6 static void Main()
    7 {
    8 List<string> l = new List<string>();
    9 l.Add("acorn"); // 0
    10 l.Add("apple"); // 1
    11 l.Add("banana"); // 2
    12 l.Add("cantaloupe"); // 3
    13 l.Add("lettuce"); // 4
    14 l.Add("onion"); // 5
    15 l.Add("peach"); // 6
    16 l.Add("pepper"); // 7
    17 l.Add("squash"); // 8
    18 l.Add("tangerine"); // 9
    19
    20 // This returns the index of "peach".
    21 int i = l.BinarySearch("peach");
    22 Console.WriteLine(i);
    23
    24 // This returns the index of "banana".
    25 i = l.BinarySearch("banana");
    26 Console.WriteLine(i);
    27
    28 // This returns the index of "apple".
    29 i = l.BinarySearch("apple");
    30 Console.WriteLine(i);
    31
    32 Console.ReadKey();
    33 }
    34 }

    输出:

    6
    2
    1

      描述。上述程序从List中找出了“peach”、“banana”,和“apple”这三个字符串的位置的值。注意List中的项是按照字母顺序排列的。如果List或者数组没有经过排序,使用BinarySearch方法将会得不到正确结果。至于是按照数值大小、字母顺序,或者ASCII来排序,都是可以的。

      比较基准

      在针对一个较大的集合进行搜索时,binary搜索比linear搜索的效率要高很多,对于元素个数小于100的集合,BinarySearch较慢,可能是执行时的资源消耗导致的。

      理解BinarySearch

      我们注意到Wikipedia对binary搜索的陈述:“makes progressively better guesses, and closes in on the location of the sought value by selecting the middle element in the pan.”参见Wikipedia的文章“Binary Search Algorithm”。MSDN对List的BinarySearch方法作了如下陈述:“返回元素基于0的索引值”。然而,必须使用一个排序过的List。

      字典是什么?

      这里我们提到字典是恒定的查找时间哈希表。对于我所用到的数据,不管List采用哪种排序算法都没有字典高效快速。一个显然的情况是,你必须为大多数的方案挑选字典。参见上述比较基准,随着集合元素的增加,BinarySearch方法比linear搜索更高效。

      对于非常较大的集合,比如有着上百万的元素,建立起一个字典将会消耗掉由查找操作所节省下来的时间。然而,我发现这种情况并不常见。

      总结

      这篇文章讲述了在什么样的情况下可以使用List类型的BinarySearch方法。针对大集合,BinarySearch使用了一个比迭代搜索更好的算法,但是对于小集合,其效率又通常低于字典。我建议你在每一次考虑BinarySearch方法时做一个性能监测。你可以从Array.BinarySearch方法这篇文章中了解.NET Framework内部的Array.BinarySearch的信息。

      本文翻译自:C# BinarySearch List 相比原文,译文作了适当修改。

  • 相关阅读:
    HDU 1495 广度优先搜索
    oj 1792:迷宫 广搜和深搜
    oj 1756:八皇后 搜索
    OJ1700 八皇后问题 基本搜索算法
    PAT A1020
    PAT A1103
    PAT A1046 Shortest Distance
    PAT A1059
    PAT B1013
    二分查找
  • 原文地址:https://www.cnblogs.com/hans_gis/p/2123257.html
Copyright © 2011-2022 走看看