泛型算法之二分查找实现,及简单测试。查找范围可以是C++内置指针或者容器的迭代器,查找内容可以是char,int等类型
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <stack>
using namespace std;
template <typename Randomaccessiterator, typename T>
Randomaccessiterator BinarySearch(Randomaccessiterator begin, Randomaccessiterator end, T key)
{
auto cpy_end = end;
end--;
int len;
auto mid = begin;
while (begin <= end)
{
len = end - begin;
mid = len / 2 + begin;
if (key< *mid)
end = mid - 1;
else if (key>*mid)
begin = mid + 1;
else
return mid;
}
return cpy_end;
}
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int main()
{
cout << *BinarySearch(a, a + 10, 3)<<endl;
vector<char> cvec;
for (int i = 0; i < 10; ++i)
cvec.push_back('a' + i);
auto result = BinarySearch(cvec.begin(), cvec.end(), 'c');
if (result != cvec.end())
cout << *result << endl;
result = BinarySearch(cvec.begin(), cvec.end(), 'v');
if (result != cvec.end())
cout << *result << endl;
else
cout << "not find" << endl;
}
测试结果