数组和向量的二分查找

数组二分查找

#include<iostream>
using namespace std;

template <typename T>

int binary_search_array(const T& key,const T data[],int N)
{
    if(N<0)
        return -1;
    int low=0;
    int high=N-1;
    while(low<=high)
    {
        int mid=low+(high-low)/2;
        if(key<data[mid])
            high=mid-1;
        else if(key>data[mid])
            low=mid+1;
        else
            return mid;
    }
    return -1;
}

int main()
{
    int a[5]={1,2,3,4,5};
    cout<<binary_search_array(5,a,5);
    system("pause");
    return 0;
}

向量二分查找,参照c++模板库,返回值不再是key的位置,而是bool值

#include<iostream>
#include<vector>
using namespace std;

template <typename T,typename iterator>
bool binary_search_iterator(const T& key,iterator L,iterator R)
{
    while(L<R)
    {
        iterator M=L+(R-L)/2;
        if(key<*M)
            R=M;
        else if(key>*M)
            L=M+1;
        else
            return true;
    }
    return false;
}
原文地址:https://www.cnblogs.com/wangtianning1223/p/11433279.html