插值查找:
是在折半查找的基础上的优化,提高了查找的效率,折半查找中mid=(low+high)/2,而在插值查找中mid=low+(value-a[low])/(a[high]-a[low])*(high-low);
#include<iostream>
#include<bits/stdc++.h>
#include<vector>
using namespace std;
//快速排序
void qsort(int a[], int left, int right) {
if (left > right) {
return;
}
int t = a[left];
int low = left;
int high = right;
while (low < high) {
while (a[high] >= t && low < high) {
high--;
}
while (a[low] <= t && low < high) {
low++;
}
if (low < high) {
swap(a[low], a[high]);
}
}
swap(a[left], a[low]);
qsort(a, left, low - 1);
qsort(a, low + 1, right);
}
//查找(找到,返回下标,没找到,返回-1)
int binarysearch(int a[],int low,int high, int value) {
if (low > high) {
return -1;
}
else {
int mid = low + (value - a[low]) / (a[high] - a[low]) * (low + high);
if (a[mid] == value) {
return mid;
}
else if (value < a[mid]) {
return binarysearch(a, low, mid - 1, value);
}
else {
return binarysearch(a, mid + 1, high, value);
}
}
}
int main() {
int a[6] = { 2,3,5,0,4,1 };
int value;
cin >> value;
qsort(a, 0, 5);
/*for (int i = 0; i < 6; ++i) {
cout << a[i] << " ";
}*/
cout<<binarysearch(a,0,5,value)<<endl;
return 0;
}