เมธอด Array.BinarySearch(Array, Object) ใน C# ใช้ในการค้นหาอาร์เรย์ที่มีการจัดเรียงแบบหนึ่งมิติทั้งหมดสำหรับองค์ประกอบเฉพาะ โดยใช้อินเทอร์เฟซ IComparable ที่ปรับใช้โดยแต่ละองค์ประกอบของอาร์เรย์และโดยวัตถุที่ระบุ
ไวยากรณ์
public static int BinarySearch (Array arr, object val);
ด้านบน arr คืออาร์เรย์ 1-D ที่จัดเรียงแล้ว ในขณะที่ 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