#include<iostream>
#include<Windows.h>
using namespace std;
#include<vector>
#include<algorithm>
//二分查找法(必须在有序的序列中查找)
//bool binary_search(iterator begin, iterator end, value);
//查找指定的元素value,找到返回true,否则返回false
void test0601()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//v.push_back(2);如果是无序序列,查找结果未知
double t0 = GetTickCount()/1000.0;//测量不出来,无法精确到us
int ret=binary_search(v.begin(), v.end(), 9);
double t1 = GetTickCount()/1000.0 - t0;
if (ret)
{
cout << "找到了" <<"用了"<< t1 << endl;
}
else
{
cout << "未找到" << endl;
}
//对比二分法查找和普通查找的速度
t0 = GetCurrentTime() / 1000.0;
vector<int>::iterator it=find(v.begin(), v.end(), 5);
t1 = GetTickCount()/1000.0 - t0;
if (it == v.end())
{
cout << "未找到" << endl;
}
else
{
cout << "找到了" << "用了" << t1 << endl;
}
}
int main()
{
test0601();
system("pause");
return 0;
}
网友评论