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("\nElement 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