泛型算法之二分查找

泛型算法之二分查找实现,及简单测试。查找范围可以是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;
}

测试结果
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值