1. 二分查找、插值查找和斐波那契查找
#include <iostream>
using namespace std;
//顺序表查找,又叫线性查找,一个一个匹配
int sequential_search( int* a, int n,int key){
int i=n-1;
while ( a[i]!=key &&i>=0)
{
i--;
}
return i; //返回-1 说明查找失败
}
//二分查找
int binary_search ( int* a, int n, int key){
int low, high, mid;
low= 1;
high= n;
while ( low<=high)
{
mid= (low +high) /2;
if ( key <a[mid])
high=mid-1;
else if (key >a[mid])
low= mid+1;
else
return mid;
}
return 0;
}
//插值查找,适用于分布均匀的查找表
int interpolation_search( int* a, int n, int key){
int low, high, mid;
low= 1;
high= n;
while ( low<=high)
{
mid= low +( high- low) *( key -a[low]) /( a[high] -a[low]);
if ( key <a[mid])
high=mid-1;
else if (key >a[mid])
low= mid+1;
else
return mid;
}
return 0;
}
int fibonacci( int k ){
if ( k==0) return 0;
if ( k==1) return 1;
else return fibonacci( k-1)+fibonacci(k-2);
}
int fibonacci_search ( int* a, int n, int key){
int low, high, mid, i, k;
low= 1;
high= n;
k=0;
while ( n>fibonacci( k) -1)
k++;
for ( i=n; i< fibonacci( k)-1 ;i++)
a[i] = a[n];
while (low <=high){
mid = low+ fibonacci( k-1 ) -1;
if ( key< a[mid])
{
high = mid-1;
k--;
}
else if (key > a[mid])
{
low= mid+1;
k-=2;
}
else{
if ( mid<=n)
{
return mid;
}
else
return n;
}
}
return 0;
}
int main(){
int a[]={12, 23, 33, 45, 56, 66, 74, 83 ,124, 135, 186, 201 , 1000 ,2000, 3000};
cout<< sequential_search( a, 15, 1000)<<endl;
cout<<binary_search( a,15 ,74)<<endl;
cout<<interpolation_search( a ,15,74)<<endl;
int b[100]={0 ,1 ,16 ,24, 35, 47, 59, 62, 73, 88, 99};
cout<<fibonacci_search( b, 10, 59)<<endl;
cout<<fibonacci( 23);
return 0;
}