List<T>.BinarySearch(T item) **सॉर्टेड** लिस्ट में बाइनरी सर्च करके तत्व का **शून्य-आधारित इंडेक्स** लौटाता है। लिस्ट **सॉर्टेड होनी चाहिए**।
उदाहरण
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("तत्व 250 इंडेक्स पर: " + index);
}
}
आउटपुट
तत्व 250 इंडेक्स पर: 3
लौटाए गए मान
- ≥ 0: तत्व मिला, इंडेक्स लौटाया।
- < 0: तत्व नहीं मिला; बिटवाइज़ कॉम्प्लीमेंट (
~index) वह इंडेक्स देता है जहां इन्सर्ट करना चाहिए।
int notFound = list.BinarySearch(200); // -4 (नहीं मिला) int insertIndex = ~notFound; // 3 (220 और 250 के बीच) list.Insert(insertIndex, 200); // सॉर्टेड क्रम बनाए रखने के लिए इन्सर्ट
कस्टम तुलनाकर्ता
list.BinarySearch(item, customComparer);
आवश्यकताएं
- लिस्ट **पहले से सॉर्टेड** होनी चाहिए (अन्यथा परिणाम अप्रत्याशित)।
- तत्व
IComparable<T>लागू करे या कस्टमIComparer<T>दें। - जटिलता:
O(log n)बनामList.IndexOfकाO(n)।