二进制搜索与向量

时间:2013-08-03 05:26:53

标签: c++ vector binary-search

我有一个已排序的向量V,我希望二进制搜索最小的索引i,其中V [i] <= target。这是我目前的尝试,但它无法正常工作。

int hi= L;
int lo= 1;
int mid  = (hi+lo)/2;
while (hi>lo+1){
    if (V[mid]>=target) hi=mid;
    else lo= mid;
    mid=(hi+lo)/2;
}

1 个答案:

答案 0 :(得分:0)

   auto s=v.begin();
   auto e=v.end();
   auto L = std::distance(s, e);

  while (L > 0)
{
  auto half = L/2;
  auto mid = s;
  std::advance(mid, half);
  if (*mid < target)
    {
      s = mid;
      ++s;
      L = L - half - 1;
    }
  else
    L = half;
}
  //s is your element !

或者为什么不能将lower_bound用于< target搜索: -

#include<iostream>
#include<vector>
#include<algorithm>

typedef std::pair<int,int> mypair;

struct comp_pairs
{
   bool operator()( const mypair lhs, 
                    const int& rhs ) const 
   { return lhs.first < rhs; }
   bool operator()( const int& lhs, 
                    const mypair& rhs ) const 
   { return lhs<rhs.first; }
};

int main()        
{

std::vector<mypair> V;
V.push_back(std::make_pair(2,9));
V.push_back(std::make_pair(3,8));
V.push_back(std::make_pair(4,7));
V.push_back(std::make_pair(5,6));

int target =4;
  auto pos=std::lower_bound(V.begin(),V.end(),target,comp_pairs());

std::cout << "Position " << (pos- V.begin()) << std::endl;
}