बाइनरी सर्च की तरह, यह सूचियों को उप-सूचियों में भी अलग करता है। यह प्रक्रिया दो मध्यवर्ती मध्य मानों का उपयोग करके सूची को तीन भागों में विभाजित करती है। चूंकि सूचियों को अधिक उप-विभाजनों में विभाजित किया जाता है, इसलिए यह एक महत्वपूर्ण मान को खोजने में लगने वाले समय को कम करता है।
टर्नरी सर्च तकनीक की जटिलता
- समय जटिलता:O(log3 n)
- अंतरिक्ष जटिलता:O(1)
इनपुट और आउटपुट
Input: A sorted list of data: 12 25 48 52 67 79 88 93 The search key 52 Output: Item found at location: 3
एल्गोरिदम
ternarySearch(array, start, end, key)
इनपुट - एक क्रमबद्ध सरणी, प्रारंभ और समाप्ति स्थान, और खोज कुंजी
आउटपुट - कुंजी का स्थान (यदि पाया जाता है), अन्यथा गलत स्थान।
Begin if start <= end then midFirst := start + (end - start) /3 midSecond := midFirst + (end - start) / 3 if array[midFirst] = key then return midFirst if array[midSecond] = key then return midSecond if key < array[midFirst] then call ternarySearch(array, start, midFirst-1, key) if key > array[midSecond] then call ternarySearch(array, midFirst+1, end, key) else call ternarySearch(array, midFirst+1, midSecond-1, key) else return invalid location End
उदाहरण
#include<iostream>
using namespace std;
int ternarySearch(int array[], int start, int end, int key) {
if(start <= end) {
int midFirst = (start + (end - start) /3); //mid of first and second block
int midSecond = (midFirst + (end - start) /3); //mid of first and second block
if(array[midFirst] == key)
return midFirst;
if(array[midSecond] == key)
return midSecond;
if(key < array[midFirst])
return ternarySearch(array, start, midFirst-1, key);
if(key > array[midSecond])
return ternarySearch(array, midSecond+1, end, key);
return ternarySearch(array, midFirst+1, midSecond-1, 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 = ternarySearch(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: 52 Item found at location: 3