实现插值搜索算法的C ++程序
对于二分查找技术,列表分为相等的部分。对于插值搜索技术,该过程将尝试使用插值公式来定位精确位置。找到估计的位置后,它可以使用该位置分隔列表。由于它每次都会尝试查找准确的位置,因此减少了搜索时间。如果项目是均匀分布的,则此技术可以轻松找到项目。
插值搜索技术的复杂性
时间复杂度:一般情况下为O(log2(log2n)),最坏情况下为O(n)(当项目呈指数分布时)
空间复杂度: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
算法
InterfaceSearch(数组,开始,结束,键)
输入:排序后的数组,开始和结束位置以及搜索键
输出:键的位置(如果找到),否则位置错误。
Begin while start <= end AND key >= array[start] AND key <= array[end] do dist := key – array[start] valRange := array[end] – array[start] fraction := dist / valRange indexRange := end – start estimate := start + (fraction * indexRange) if array[estimate] = key then return estimate position if array[estimate] < key then start := estimate + 1 else end = estimate -1 done return invalid position End
范例程式码
#include<iostream> using namespace std; int interpolationSearch(int array[], int start, int end, int key) { int dist, valRange, indexRange, estimate; float fraction; while(start <= end && key >= array[start] && key <= array[end]) { dist = key - array[start]; valRange = array[end] - array[start]; //range of value fraction = dist / valRange; indexRange = end - start; estimate = start + (fraction * indexRange); //estimated position of the key if(array[estimate] == key) return estimate; if(array[estimate] < key) start = estimate +1; else end = estimate - 1; } 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 = interpolationSearch(arr, 0, n-1, searchKey)) >= 0) cout << "Item found at location: " << loc << endl; else cout << "在列表中找不到项目。" << 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