#include<iostream>
#include<cstdlib>
#include<ctime>
#define M 100000000
#define random(a,b) (rand()%(b-a+1)+a)
using namespace std;
// 在有序的一亿个数中查找一个数所用的时间 2.5us
// clock() 是以ms为单位的
bool Binarysearch(int *a, int low, int high, int x){
// 二分查找
// 并未重复调用Binarysearch函数
while (low <= high){
int mid = (low + high) / 2;
if (a[mid] == x)
return true;
else if (a[mid] > x)
high = mid - 1;
else low = mid + 1;
}
return false;
}
int main()
{
int *a=new int[M];
// a[M] M太大,直接用a[M]会报错。
int testNum = 1000000;
bool ret = false;
for (int i = 0; i < M; i++)
a[i] = i + 1;
clock_t startTime = clock();
srand((unsigned)time(NULL));
for (int i = 0; i < testNum; i++)
{
int tmp = random(M - testNum, M + testNum);
ret = Binarysearch(a, 0, M, tmp);
}
clock_t endTime = clock();
cout << 1 << endl;
cout << (endTime - startTime)*1.0 / testNum;
delete []a;
}
在一亿个数的有序数组中查找一个数所用时间
最新推荐文章于 2022-03-05 16:08:05 发布