C# 数组 - BinarySearch() 方法
C# 数组 BinarySearch() 方法使用指定的 IComparer 接口在一维排序数组中的一系列元素中搜索值,其中 IComparer 是一个用于比较两个对象的方法。
语法
以下是 C# 数组 BinarySearch() 方法的语法 -
public static int BinarySearch(Array array, object value, IComparer comparer);
参数
此函数接受以下数组 -
- Array:要搜索的一维排序数组。
- object:要搜索的值。
- IComparer:IComparer 接口的实现,用于自定义比较逻辑。如果为 null,则使用自然的 IComparer 逻辑。
返回值
如果在当前数组中找到指定值,则此函数返回该值的索引;否则,返回负数。如果未找到值,且值小于数组中的一个或多个元素。
示例 1:不使用 IComparer 使用 BinarySearch()
让我们创建一个 BinarySearch() 方法的基本示例,以显示指定元素的索引值 -
using System; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4, 5 }; int value_to_search = 4; int index = Array.BinarySearch(numbers, value_to_search); if (index >= 0) { Console.WriteLine("Index: " + index); } else { Console.WriteLine("Value not found. Insertion point: " + ~index); } } }
输出
以下是输出 -
Index: 3
示例 2:使用自定义 IComparer 进行 BinarySearch
以下示例使用 BinarySearch() 方法和自定义 icomparer,根据指定的比较器逻辑显示指定值的索引 -
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() { // 按 des 顺序排序的数组 int[] numbers = { 50, 40, 30, 20, 10 }; int valueToFind = 30; int index = Array.BinarySearch(numbers, valueToFind, new DescendingComparer()); if (index >= 0) { Console.WriteLine($"Value {valueToFind} found at index {index}."); } else { Console.WriteLine($"Value {valueToFind} not found. Insertion point: {~index}"); } } }
输出
以下是输出 -
Value 30 found at index 2.
示例 3:未找到值时
这是 BinarySearch() 方法的另一个示例。当未找到值时,此函数将基于已排序的数组返回插入索引值 -
using System; class Program { static void Main() { // 按 des 顺序排序的数组 int[] numbers = { 10, 20, 30, 40, 50 }; int valueToFind = 25; int index = Array.BinarySearch(numbers, valueToFind, null); Console.WriteLine($"Insertion point: {~index}"); } }
输出
以下是输出 -
Insertion point: 2
示例 4:字符串数组中的二分查找
在此示例中,我们使用自定义比较器 BinarySearch() 方法搜索字符串 -
using System; using System.Collections; class CaseInsensitiveComparer : IComparer { public int Compare(object x, object y) { string str1 = x as string; string str2 = y as string; if (str1 == null || str2 == null) throw new ArgumentException("Both arguments must be strings."); // 执行不区分大小写的比较 return string.Compare(str1, str2, StringComparison.OrdinalIgnoreCase); } } class Program { static void Main() { string[] fruits = { "Apple", "Banana", "Grape", "Mango", "Orange" }; string valueToSearch = "mango"; int index = Array.BinarySearch(fruits, valueToSearch, new CaseInsensitiveComparer()); if (index >= 0) { Console.WriteLine($"Value '{valueToSearch}' found at index {index}."); } else { Console.WriteLine($"Value '{valueToSearch}' not found. Insertion point: {~index}"); } } }
输出
以下是输出 -
Value 'mango' found at index 3.