标签:二分查找
#include <vector>
#include <iostream>
using namespace std;
vector<int> data;
void createData(int n){
//存储小于n的正偶数
for (int i=0;i<n;i+=2)
data.push_back(i);
}
bool search(int value,int& sign){
int start=0;int end=data.size()-1;int mid;
while(start<=end){
mid = (end + start)/2;
if (data.at(mid) == value)
{
sign = mid;
return true;
}else if (data.at(mid) < value)
{
start = mid + 1;
}else{
end = mid -1;
}
}
sign = -1;
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
createData(100);
int sign,ret;
for (int i=-1;i<120;i+=15)
{
ret = search(i,sign);
cout<<"i="<<i<<"; search返回:"<<ret<<"; sign="<<sign<<endl;
}
getchar();
return 0;
}
标签:二分查找
原文地址:http://blog.51cto.com/whish/2073477