Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Array.BinarySearch ใน C#


ภาพรวม

เมธอด Array.BinarySearch() ใช้ค้นหาดัชนีของค่าใน อาร์เรย์ที่จัดเรียงแล้ว (sorted array) โดยใช้알고อิทึมแบบทวิภาค (binary search) O(log n)

เงื่อนไขสำคัญ

  • อาร์เรย์ ต้องจัดเรียงล่วงหน้า (ascending order)
  • หากไม่จัดเรียง ผลลัพธ์ไม่ถูกต้อง

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        string[] str = { "a", "i", "m", "t" }; // ต้องจัดเรียงแล้ว
        int res = Array.BinarySearch(str, "t");
        Console.WriteLine("Index : " + res); // 3
    }
}

ผลลัพธ์

Index : 3

ค่าคืนเมื่อไม่พบ

คืนค่า bitwise complement ของดัชนีที่ควรจะอยู่: ~index (เช่น -4 หมายถึงควรอยู่ที่ดัชนี 3)

int idx = Array.BinarySearch(arr, "z"); // ไม่พบ
if (idx < 0) int insertPos = ~idx; // ตำแหน่งที่ควร insert

Overloads

  • BinarySearch(Array, Object)
  • BinarySearch(Array, Int32, Int32, Object) - ค้นในช่วง
  • BinarySearch(T[], T, IComparer) - รองรับ comparer แบบกำหนดเอง