/
二分查找
作者:Zhihang
(附:这是俺滴原创,盗用请看本程序最底下)
/
using namespace std;
int erfen(int array[],int n,int ans){
sort(array,array+n);
int left=0;
int right=n-1;
while(left<=right){
int mix=left+(right-left)/2;
if(ans==array[mix])
return mix;
if(ans<array[mix])
right=mix-1;
else if(ans>array[mix])
left=mix+1;
}
return -1;
}
int randomArray(int n,int left,int right){
assert(left<=right);
int array=new int[n];
srand(time(NULL));
for(int i=0;i<n;i++){
array[i]=rand()%(right-left+1)+left;
}
return array;
}
int* testerfen(string name,int array[],int n,int left,int right){
int zhao=rand()%(right-left+1)+left;
int clock_start=clock();
erfen(array,n,zhao);
int clock_end=clock();
cout<<name<<": "<<double(clock_end-clock_start)/CLOCKS_PER_SEC<<endl;
}
int main(){
const int n=10000000;
int *array=randomArray(n,1,n);
testerfen("二分查找",array,n,1,n);
return 0;
}
//先Ctrl+A 再Ctrl+C 最后Ctrl+V
共同学习,写下你的评论
评论加载中...
作者其他优质文章