जब सूची को क्रमबद्ध किया जाता है तो हम सूची में आइटम खोजने के लिए बाइनरी खोज तकनीक का उपयोग कर सकते हैं। इस प्रक्रिया में, पूरी सूची को दो उप-सूचियों में विभाजित किया जाता है। यदि आइटम मध्य स्थिति में पाया जाता है, तो यह स्थान लौटाता है, अन्यथा या तो बाएँ या दाएँ उप-सूची में कूद जाता है और आइटम को खोजने या सीमा से अधिक होने तक फिर से वही प्रक्रिया करता है।
द्विआधारी खोज तकनीक की जटिलता
- समय की जटिलता : ओ (1) सर्वोत्तम मामले के लिए। O(log2 n) औसत या सबसे खराब स्थिति के लिए।
- अंतरिक्ष जटिलता: ओ(1)
इनपुट और आउटपुट
Input: A sorted list of data: 12 25 48 52 67 79 88 93 The search key 79 Output: Item found at location: 5
एल्गोरिदम
binarySearch(array, start, end, key)
इनपुट - एक क्रमबद्ध सरणी, प्रारंभ और समाप्ति स्थान, और खोज कुंजी
आउटपुट - कुंजी का स्थान (यदि पाया जाता है), अन्यथा गलत स्थान।
Begin if start <= end then mid := start + (end - start) /2 if array[mid] = key then return mid location if array[mid] > key then call binarySearch(array, mid+1, end, key) else when array[mid] < key then call binarySearch(array, start, mid-1, key) else return invalid location End
उदाहरण
#include<iostream>
using namespace std;
int binarySearch(int array[], int start, int end, int key) {
if(start <= end) {
int mid = (start + (end - start) /2); //mid location of the list
if(array[mid] == key)
return mid;
if(array[mid] > key)
return binarySearch(array, start, mid-1, key);
return binarySearch(array, mid+1, end, key);
}
return -1;
}
int main() {
int n, searchKey, loc;
cout << "Enter number of items: ";
cin >> n;
int arr[n]; //create an array of size n
cout << "Enter items: " << endl;
for(int i = 0; i< n; i++) {
cin >> arr[i];
}
cout << "Enter search key to search in the list: ";
cin >> searchKey;
if((loc = binarySearch(arr, 0, n, searchKey)) >= 0)
cout << "Item found at location: " << loc << endl;
else
cout << "Item is not found in the list." << endl;
} आउटपुट
Enter number of items: 8 Enter items: 12 25 48 52 67 79 88 93 Enter search key to search in the list: 79 Item found at location: 5