标签:二分查找
#ifndef _BINARYSEARCH_H
#define _BINARYSEARCH_H
template<typename Iterator,typename T>
bool binarySearch(Iterator p, Iterator r, Iterator &rp, const T &value)
{
int n = distance(p, r);
if (n < 1)
return false;//无此元素
Iterator q = p;
advance(q, n/2);//q=[q+r]/2
if (*q == value)
{
rp = q;
return true;
}
if (*q>value)
return binarySearch(p, q,rp,value);
else
return binarySearch(q+1, r,rp, value);
}
/******************二分法查找*****************
输入;p,q,序列首末地址,
value:目标查找元素
返回:若找到元素,返回其地址,否则返回last iterator
*********************************************/
template<typename Iterator,typename T>
Iterator binarySearch(Iterator p, Iterator r, const T &value)
{
static Iterator k = r;//static局部变量,仅做第一次初始化,且在多次调用中保存改变的值
int n = distance(p, r);
if (n < 1)
return k;
Iterator q = p;
advance(p, n / 2);
if (*q == value)
return q;
if (*q>value)
return binarySearch(p, q, value);
else
return binarySearch(q + 1, r, value);
}
#endif // !_BINARYSEARCH_H
#include <cstdio>
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include "binarySearch.h"
using namespace std;
int main(int argc, char** argv)
{
int a[] = { 0, 1, 2, 3, 5, 6, 7, 8, 9 };
int b;
vector<int> va=vector<int>(a, a+9);
vector<int>::iterator k;
//binary_search(va.begin(), va.end(), 0);
/*if (binarySearch(va.begin(), va.end(), k, 3))
b = distance(va.begin(), k);
else
b = -1;*/
b = distance( va.begin(),binarySearch(va.begin(), va.end(), 9));
cout << b << endl;
system("pause");
}
标签:二分查找
原文地址:http://blog.csdn.net/u010177286/article/details/45535367