带 C# 示例的 Array.BinarySearch(Array, Object) 方法
C# 中的 Array.BinarySearch(Array, Object) 方法用于使用数组中每个元素以及指定对象实现的 IComparable 接口在整个一维已排序数组中搜索特定元素。
语法
public static int BinarySearch (Array arr, object val);
上面,arr 是已排序的一维数组,val 是要搜索的对象。
示例
using System; public class Demo { public static void Main() { int[] intArr = {5, 10, 15, 20}; Array.Sort(intArr); Console.WriteLine("Array elements..."); foreach(int i in intArr) { Console.WriteLine(i); } Console.Write("Element 25 is at index = " + Array.BinarySearch(intArr, 20)); } }
输出
Array elements... 5 10 15 20 Element 25 is at index = 3
示例
using System; public class Demo { public static void Main() { string[] strArr = {"John", "Tim", "Fedric", "Gary", "Harry", "Damien"}; Array.Sort(strArr); Console.WriteLine("Array elements..."); foreach(string s in strArr) { Console.WriteLine(s); } Console.Write("Element Gary is at index = " + Array.BinarySearch(strArr, "Gary")); Console.Write("
Element Tom is at index = " + Array.BinarySearch(strArr, "Tom")); } }
输出
Array elements... Damien Fedric Gary Harry John Tim Element Gary is at index = 2 Element Tom is at index = -7
广告