C# ArrayList - BinarySearch() 方法
C# ArrayList BinarySearch() 方法用于在已排序的 ArrayList 中高效地搜索特定元素。
此方法执行二分查找,比线性查找快得多,但需要 ArrayList 已排序。
语法
以下是 C# ArrayList BinarySearch() 方法的语法 -
public virtual int BinarySearch(object value); public virtual int BinarySearch(object value, IComparer comparer); public virtual int BinarySearch(int index, int count, object value, IComparer comparer);
参数
此方法接受以下参数 -
- value:必须指定要在 ArrayList 中搜索的对象。对于引用类型,可以为 null。
- comparer:可选,使用 Icomparer 实现自定义比较。
- index:搜索范围的起始索引,从 0 开始。
- count:搜索范围内元素的数量。
返回值
如果找到该值,此方法将返回该值在已排序 ArrayList 中的起始索引,从 0 开始。否则,返回负数。
示例 1:添加范围内的元素
这是 ArrayList 集合的基本示例,用于演示如何使用 BinarySearch 在 ArrayList 中搜索特定对象 -
using System; using System.Collections; class Program { static void Main() { ArrayList arrayList = new ArrayList { 10, 20, 30, 40, 50 }; // 执行二分查找 int index = arrayList.BinarySearch(30); if (index >= 0) { Console.WriteLine($"Element found at index: {index}"); } else { Console.WriteLine("Element not found"); } } }
输出
以下是输出 -
Element found at index: 2
示例 2:如果 ArrayList 未排序会怎样
让我们看另一个 BinarySearch() 方法的示例。如果 ArrayList 未排序,我们需要先对其进行排序,然后再执行搜索操作 -
using System; using System.Collections; class Program { static void Main() { ArrayList arrayList = new ArrayList { 10, 30, 20, 60, 40, 15 }; arrayList.Sort(); // 执行二分查找 int index = arrayList.BinarySearch(30); if (index >= 0) { Console.WriteLine($"Element found at index: {index}"); } else { Console.WriteLine("Element not found"); } } }
输出
以下是输出 -
Element found at index: 3
示例 3:使用自定义比较器
在此示例中,我们使用带有自定义比较器的 BinarySearch 方法从 ArrayList 中查找特定元素 -
using System; using System.Collections; class DescendingComparer: IComparer { public int Compare(object x, object y) { // 逆序比较 return Comparer.Default.Compare(y, x); } } class Program { static void Main() { // 创建 ArrayList 并按降序排序 ArrayList arrayList = new ArrayList { 50, 40, 30, 20, 10 }; arrayList.Sort(new DescendingComparer()); // 使用自定义比较器执行二分搜索 int index = arrayList.BinarySearch(30, new DescendingComparer()); if (index >= 0) { Console.WriteLine($"Element found at index: {index}"); } else { Console.WriteLine("Element not found"); } } }
输出
以下是输出 -
Element found at index: 2
示例 4:搜索元素范围
在本例中,我们使用 BinarySearch() 方法搜索具有以下范围的元素:-
using System; using System.Collections; class Program { static void Main() { // 创建并排序 ArrayList ArrayList arrayList = new ArrayList { 10, 20, 30, 40, 50 }; arrayList.Sort(); // 在特定范围内执行二分查找 int index = arrayList.BinarySearch(1, 3, 40, null); if (index >= 0) { Console.WriteLine($"Element found at index: {index}"); } else { Console.WriteLine("Element not found in the range"); } } }
输出
以下是输出 -
Element found at index: 3