การค้นหาแบบเอ็กซ์โพเนนเชียลเรียกอีกอย่างว่าการค้นหาแบบทวีคูณหรือแบบควบ กลไกนี้ใช้เพื่อค้นหาช่วงที่อาจแสดงคีย์การค้นหา ถ้า L และ U เป็นขอบเขตบนและล่างของรายการ ดังนั้น L และ U จะเป็นยกกำลัง 2 สำหรับส่วนสุดท้าย U คือตำแหน่งสุดท้ายของรายการ ด้วยเหตุนี้จึงเรียกว่าเลขชี้กำลัง
หลังจากพบช่วงเฉพาะแล้ว จะใช้เทคนิคการค้นหาแบบไบนารีเพื่อค้นหาตำแหน่งที่แน่นอนของคีย์การค้นหา
ความซับซ้อนของเทคนิคการค้นหาแบบเอ็กซ์โปเนนเชียล
- ความซับซ้อนของเวลา: O(1) สำหรับกรณีที่ดีที่สุด O(log2 i) สำหรับกรณีทั่วไปหรือแย่ที่สุด โดยที่ i คือตำแหน่งที่มีแป้นค้นหาอยู่
- ความซับซ้อนของอวกาศ: O(1)
อินพุตและเอาต์พุต
Input: A sorted list of data: 10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995 The search key 780 Output: Item found at location: 16
อัลกอริทึม
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
exponentialSearch(array, start, end, key)
ป้อนข้อมูล: อาร์เรย์ที่จัดเรียง ตำแหน่งเริ่มต้นและสิ้นสุด และแป้นค้นหา
ผลลัพธ์: ตำแหน่งของกุญแจ (หากพบ) มิฉะนั้น ตำแหน่งที่ไม่ถูกต้อง
Begin if (end – start) <= 0 then return invalid location i := 1 while i < (end - start) do if array[i] < key then i := i * 2 //increase i as power of 2 else terminate the loop done call binarySearch(array, i/2, i, key) 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 exponentialSearch(int array[], int start, int end, int key){
if((end - start) <= 0)
return -1;
int i = 1; // as 2^0 = 1
while(i < (end - start)){
if(array[i] < key)
i *= 2; //i will increase as power of 2
else
break; //when array[i] corsses the key element
}
return binarySearch(array, i/2, i, key); //search item in the smaller range
}
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 = exponentialSearch(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: 20 Enter items: 10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995 Enter search key to search in the list: 780 Item found at location: 16