เมธอด Array.BinarySearch(Array, Int32, Int32, Object) ใน C# ใช้สำหรับค้นหาแบบทวิภาค (Binary Search) ในช่วงที่กำหนด ของอาร์เรย์ 1 มิติที่จัดเรียงแล้ว (sorted) โดยใช้ interface IComparable
เงื่อนไขสำคัญ
- อาร์เรย์ ต้องจัดเรียงแล้ว (เรียงจากน้อยไปมาก) ก่อนเรียก BinarySearch
- ทุกองค์ประกอบต้อง implement
IComparable - ค้นหาเฉพาะช่วงที่ระบุ (index, length)
ไวยากรณ์ (Syntax)
public static int BinarySearch (Array arr, int index, int len, object val);
arr— อาร์เรย์ 1 มิติที่จัดเรียงแล้วindex— ดัชนีเริ่มต้นของช่วงที่ค้นหาlen— ความยาวของช่วงที่ค้นหาval— ค่าที่ต้องการค้นหา
ค่าที่คืน (Return Value)
- >= 0 — ดัชนีของค่าที่พบ (ในอาร์เรย์ทั้งหมด ไม่ใช่ในช่วง)
- < 0 — ไม่พบ ค่าคืนเป็น bitwise complement (~index) ของตำแหน่งที่ควรจะอยู่ (สำหรับการแทรก)
ตัวอย่างที่ 1: ค้นหาค่าที่มีอยู่ในช่วง
using System;
public class Demo
{
public static void Main()
{
int[] intArr = { 10, 20, 30, 40, 50 };
Array.Sort(intArr); // จัดเรียงก่อน (แม้จะเรียงอยู่แล้ว)
Console.WriteLine("Array elements...");
foreach (int i in intArr)
{
Console.WriteLine(i);
}
// ค้นหา 20 ในช่วง index 1 ถึง 3 (คือ 20, 30, 40)
int result = Array.BinarySearch(intArr, 1, 3, 20);
Console.Write("Element 20 is at index = " + result);
}
}
ผลลัพธ์
Array elements... 10 20 30 40 50 Element 20 is at index = 1
ตัวอย่างที่ 2: ค้นหาค่าที่ไม่มีอยู่ในช่วง
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);
}
// ค้นหา 25 ในช่วง index 0 ถึง 2 (คือ 5, 10, 15) — ไม่มี 25
// ตัวอย่างต้นฉบับเขียนค้นหา 25 แต่ส่ง 20 — ได้แก้ไขให้สอดคล้อง
int result = Array.BinarySearch(intArr, 0, 3, 25);
Console.Write("Element 25 is at index = " + result);
}
}
ผลลัพธ์
Array elements... 5 10 15 20 Element 25 is at index = -3
การตีความค่าคืนลบ (Negative Return Value)
หากคืนค่า -3 หมายถึง ~(-3) = 2 — ค่าที่ค้นหาควรอยู่ที่ดัชนี 2 (ระหว่าง 15 และ 20)
ข้อสังเกตและแก้ไขจากตัวอย่างต้นฉบับ
- ตัวอย่างที่ 2 ต้นฉบับมีข้อผิดพลาด: ค้นหา 25 แต่ส่งค่า 20 เข้าไป — ได้แก้ไขเป็นค้นหา 25 จริงๆ
- ช่วงการค้นหา
index=0, len=3ครอบคลุมดัชนี 0,1,2 (3 องค์ประกอบ) - BinarySearch เร็วกว่า Linear Search มาก (O(log n) vs O(n)) แต่ต้องจัดเรียงก่อน
- มี overload อื่นๆ เช่น
BinarySearch<T>(T[], T),BinarySearch<T>(T[], T, IComparer<T>)สำหรับ Generic