#include <bits/stdc++.h>
#include <time.h>
using namespace std;
#define N 1000
template<typename T>
int line_search(T a[],T flagnum, T n)
{
int i = 0;
a[n] = flagnum;
while(a[i] != flagnum)
i++;
return i;//返回搜索结果的下标
}
int main()
{
int n = 153;
int a[N]= {684,435,237,140,475,585,249,738,437,541,
940,343,514,362,629,466,582,641,314,59,
982,166,450,314,595,703,436,795,148,17,
684,435,237,140,475,585,249,738,437,541,
940,343,514,362,629,466,582,641,314,59,
982,166,450,314,595,703,436,795,148,17,
684,435,237,140,475,585,249,738,437,541,
940,343,514,362,629,466,582,641,314,59,
982,166,450,314,595,703,436,795,148,17,
684,435,237,140,475,585,249,738,437,541,
940,343,514,362,629,466,582,641,314,59,
982,166,450,314,595,703,436,795,148,17,
684,435,237,140,475,585,249,738,437,541,
940,343,514,362,629,466,582,641,314,59,
982,166,450,314,595,703,436,795,148,17,77777,88767,66666};
int flagnum=88767;
//one:
cout<<"1:"<<endl;
clock_t time1 = clock();
int k=n+1;
for(int i=0;i<n;i++){
if(a[i] == flagnum){
k=i;
break;
}
}
if(a[k]!=flagnum)
cout<<"NO"<<endl;
else cout<<k<<endl;
clock_t time2 = clock();
cout <<"Running Time == "<<(double)(time2 - time1) / CLOCKS_PER_SEC << endl;
//two:
cout<<"2:"<<endl;
clock_t time3= clock();
int i = 0;
a[n] = flagnum;//制定终止条件 防止无限循环
while(a[i] != flagnum)
i++;
if(i==n)
cout<<"NO"<<endl;
else cout<<k<<endl;
clock_t time4 = clock();
cout <<"Running Time == "<<(double)(time4 - time3) / CLOCKS_PER_SEC << endl;
//three:
cout<<"3:"<<endl;
clock_t time5= clock();
int i2 = line_search(a,flagnum,n);
if(i2==n)
cout<<"NO"<<endl;
else cout<<k<<endl;
clock_t time6 = clock();
cout <<"Running Time == "<<(double)(time6 - time5) / CLOCKS_PER_SEC << endl;
return 0;
}
/**
//数据规模小,无法比较1,2的差距。
1:
151
Running Time == 0
2:
151
Running Time == 0
3:
151
Running Time == 0.001
*/
【菜鸟er】搜索专题_优化线性搜索
最新推荐文章于 2021-08-15 04:33:22 发布