折半查找
折半查找
#include<time.h> #include<cstdio> #include<iostream> #include<algorithm> using namespace std; const int n=10; int Erfen(int *a,int n,int key)//开始查找 { int low=0; int high=n-1; int middle; while(low<=high) { middle=(low+high)/2; if(a[middle]==key) return middle; else if(a[middle]>key) high=middle-1; else low=middle+1; } return -1; } int main() { int a[n],key; key=6;//关键字自定义 clock_t start,end; start=clock();//开始计时 srand(time(0)); //种子 cout<<"key= "<<key<<endl; for(int i=0;i<n;i++) { a[i]=rand()%(n-2)+1;//产生随机数,并给数组 cout<<a[i]<<" "; } cout<<endl; sort(a,a+n); cout<<"排序后的数组:"<<endl; for(i=0;i<n;i++) { cout<<a[i]<<" "; } cout<<endl; int temp=Erfen(a,n,key);//查找 if(temp==-1) cout<<"no found"<<endl; else cout<<"数字所在位置的数组下标是:"<<temp<<endl; end=clock();//计时结束(一般时间太短,显示为0.00000等) cout<<"time: "; printf("%6.5f\n",end-start); return 0; }


浙公网安备 33010602011771号