#include <iostream> using namespace std; #define N 10 int fib(int n) { if(n == 0) { return 0; } else if(n == 1) { return 1; } else { return (fib(n-1) + fib(n-2)); } } //普通查找: int sequenctial_Search(int *a,int n,int key) { int i; a[0] = key; i = n; while(a[i] != key) { i--; } return i; } //折半查找: int Binary_Search(int *a,int n,int key) { int low,high,mid; low = 0; high = n-1; while(low <= high) { mid = (int)(low + high)/2; if(key < a[mid]) { high = mid-1; } else if(key > a[mid]) { low = mid+1; } else return mid; } return 0; } //差值查找(斐波那契查找) int Fib_Search(int *a,int n,int key) { int low,high,mid,k; low = 0; k = 0; while(n > fib(k)-1) { k = k + 1; } // for(i = n;i < fib(k)-1;i++) // { // a[i] = -1; // } high = fib(k)-1; // cout << k<<endl; while(low <= high) { mid = low + fib(k-1)-1; if(key < a[mid]) { high = mid - 1; k = k - 1; } else if(key > a[mid]) { low = mid + 1; k = k - 2; } else { if(mid <= n) return mid; else return -1; } } return 0; } int main() { int a[N] = {1,2,4,5,6,8,9,10,20,31}; int key,result; cout << "please input the key:"; cin >> key; result = sequenctial_Search(a,N,key); cout<<result<<endl; result = Binary_Search(a,N,key); cout << result<<endl; result = Fib_Search(a,N,key); cout<<result<<endl; return 0; }