指数搜索
指数搜索也称为倍增搜索或跳跃搜索。这种机制用于查找搜索键可能存在的范围。如果 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP