二分查找法(C++ 模板实现)

本文详细介绍了如何使用C++模板实现经典的二分查找算法,通过模板的泛型编程特性,使得该算法可以应用于不同类型的有序数组中,提高了代码的复用性和效率。
摘要由CSDN通过智能技术生成
/*算法总结
  二分查找法:
  二分查找法的前提是数据已经排序,时间平均复杂度为 O(lgn)
  欢迎转载,转载请注明作者 openxmpp@163.com
*/


#include <iostream>
#include <stdio.h>
using namespace std;
#include <vector>
using std::vector;
#include <algorithm>


/**
 * @brief binarySearch 二分查找
 * @param array 排序后的数组
 * @param value 待查找的参数
 * @return true on success ,false on failure
 */
template<typename T>
bool binarySearch(vector<T> &array,T value)
{
    int low = 0;
    int high = array.size () -1;
    while ( low <= high )
    {
        int middle = ( low + high ) /2;
        if ( array[middle] == value )
        {
            return true;
        }
        else if ( array[middle] > value )
        {
            high = middle - 1;
        }
        else if ( array[middle] < value )
        {
            low = middle + 1;
        }
    }
    return false;
}


void unitTest()
{
    vector<int> vec;
    for ( int i = 0 ; i < 100 ; i += 2 )
    {
        vec.push_back (i);
    }
    bool result = binarySearch<int>(vec,29);
    cout << "search result for [29]  " << result<<endl;
    result = binarySearch<int>(vec,16);
    cout << "search result for [16]  " << result<<endl;


    vector<string> strVect;
    strVect.push_back ("world");
    strVect.push_back ("hello");
    strVect.push_back ("b");
    strVect.push_back ("a");
    strVect.push_back ("i love cpp");
    sort(strVect.begin (),strVect.end ());


    result = binarySearch<string>(strVect,"notfind");
    cout << "search result for [notfind]  " << result<<endl;


    result = binarySearch<string>(strVect,"world");
    cout << "search result for [world]  " << result<<endl;
}


int main(int argc, char *argv[])
{
    unitTest ();
    return 0;
}




下面是递归的实现

#include <iostream>
using 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值