数组二分查找

#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;
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2021-11-18
  • 2021-10-30
猜你喜欢
  • 2022-12-23
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2021-09-02
相关资源
相似解决方案