ภาพรวม
เมธอด BinarySearch() ใช้ค้นหาองค์ประกอบใน รายการที่จัดเรียงแล้ว (sorted list) โดยใช้ алгоритםแบบทวิภาค (binary search) คืนค่าดัชนี (index) ขององค์ประกอบที่พบ ทำงานได้กับข้อมูลตัวเลข ตัวอักษร และสตริง
เงื่อนไขการใช้งาน
- รายการ ต้องจัดเรียงล่วงหน้า (ascending order)
- หากไม่จัดเรียง ผลลัพธ์จะไม่ถูกต้อง
- คืนค่า index (0-based) หากพบ; หากไม่พบ คืนค่าตัวเลขลบ (bitwise complement ของ index ที่ควรจะอยู่)
ตัวอย่างโค้ดเต็ม
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
List list = new List { 70, 150, 220, 250, 300 };
int index = list.BinarySearch(250);
Console.WriteLine("Element 250 at Index: " + index); // 3
}
}
ผลลัพธ์
Element 250 at Index: 3
การใช้งานกับ Array
int[] arr = { 10, 20, 30, 40, 50 };
int idx = Array.BinarySearch(arr, 30); // 2
ประสิทธิภาพ
- ความซับซ้อนเวลา: O(log n) เร็วกว่าการค้นหาเชิงเส้น (O(n)) มากสำหรับข้อมูลขนาดใหญ่
- ต้องการหน่วยความจำคงที่ O(1)