#include<iostream>
using namespace std;
int search(const int*, int, int);
int main()
{
int arr[6] = {1,2,3,4,10,20};
int find = search(arr, 6, 10);
if(find == -1)
cout << "没有找到!" << endl;
else
cout << arr[find] << endl;
return 0;
}
int search(const int* arr, int size, int key)
{
int tou, wei, zhong;
tou = 0;
wei = size - 1;
while(tou <= wei)
{
zhong = tou + (wei - tou) * (key - arr[tou]) / (arr[wei] - arr[tou]); //拉法朗日算法
if(key == arr[zhong])
{
return zhong;
}
else if(key < arr[zhong])
{
wei = zhong - 1;
}
else
tou = zhong + 1;
}
return -1;
using namespace std;
int search(const int*, int, int);
int main()
{
int arr[6] = {1,2,3,4,10,20};
int find = search(arr, 6, 10);
if(find == -1)
cout << "没有找到!" << endl;
else
cout << arr[find] << endl;
return 0;
}
int search(const int* arr, int size, int key)
{
int tou, wei, zhong;
tou = 0;
wei = size - 1;
while(tou <= wei)
{
zhong = tou + (wei - tou) * (key - arr[tou]) / (arr[wei] - arr[tou]); //拉法朗日算法
if(key == arr[zhong])
{
return zhong;
}
else if(key < arr[zhong])
{
wei = zhong - 1;
}
else
tou = zhong + 1;
}
return -1;
}
//优点:对于数据均匀容器来说,拉格朗日插值查找法效率非常高,但是对于数据不均匀的容器,比如说一个容器里面有100个数字,前99个为1-99,最后一个为100000,如果我们要查找99的话,要循环99次才行