标签:
#include<cstdio> #include<cstdlib> #include<cstring> //折半查找 int Binary_Search(int *a,int n,int key){ int cnt = 0; int low,high,mid; low = 1; high = n; while(low <= high){ cnt++; mid = (low + high) >> 1; // 算术位运算 if(key < a[mid]) high = mid - 1; else if(key > a[mid]) low = mid + 1; else { printf("共查找了 %d 次\n",cnt); return mid; } } return 0; } //插值查找 int Binary_Search2(int *a,int n,int key){ int cnt = 0; int low,high,mid; low = 1; high = n; while(low <= high){ cnt++; 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 { printf("共查找了 %d 次\n",cnt); return mid; } } return 0; } //斐波那契查找 int Fibonacci_Search(int *a,int n,int key){ int cnt = 0; int low,high,mid,i,k; int F[11] = {0,1,1,2,3,5,8,13,21,34,55}; low = 1; high = n; k = 0; while(n>F[k]-1) k++; for(i=n;i<F[k]-1;i++) a[i] = a[n]; //将不满的数值补全 while(low<=high){ cnt++; mid = low + F[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{ printf("共查找了 %d 次\n",cnt); if(mid<= n) return mid; else return n; } } return 0; } int main(){ int a[11] = {0,1,16,24,35,47,59,62,73,88,99}; printf("折半查找 59 的位置 %d\n\n",Binary_Search(a,10,59)); printf("插值查找 59 的位置 %d\n\n",Binary_Search2(a,10,59)); printf("斐波那契查找 59 的位置 %d\n\n",Fibonacci_Search(a,10,59)); return 0; }
标签:
原文地址:http://www.cnblogs.com/zhuozhuo/p/5425484.html