我一直试图解决一个问题,我有一个数组让我们说A [] = {5,9,11,15};和2个带值的变量让我们说2和10.i需要找出数组的任何元素是否属于(2,10),即它的值在2(排除)到10(包括)之间。我可以简单地转一个循环搜索> if(2 = A [i])<但是这不会在数组大小的值上工作让我们说10 ^ 5.而且我尝试使用修改后的二进制搜索,它返回的索引值小于或等于重要的价值提供但失败。谁能为我提供快速的算法呢? 编辑:pos这里的元素数量breaaking是数组FLOOR是函数(修改二进制)
int Floor(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return l;
}
int Floor(int A [],int size,int key)
{ //错误检查
if(key&lt; A [0]) 返回-1; //没有底价
return Floor(A, 0, size, key);
}
//
int ret=Floor(breaaking,pos,mini);
printf("%d\n",ret);
printf("mini is %d and maxi is %d",mini,maxi);
if(pos==0)
{
printf("There is no breaking point in the array :) (pos==0)\n");
printf("Yes\n");
}
else if(ret==-1)
{
printf("Mini is smaller than smallest element of breaking\n");
if(breaaking[0]<maxi)
{
printf("but maxi is greater than smallest element hece it lies between so:\n");
printf("No\n");
}
else {
printf("even maxi is less than smallest element hence:\n");
printf("Yes\n");
}
}
else if(ret==pos-1)
{
printf("mini is either equal to last element of breaker set or greater than it\n");
if(mini==breaaking[pos-1])
{
printf("mini is equal to the last element hence\n");
printf("No\n");}
else
{
printf("mini is greater than the last element hence:");
printf("Yes\n");
}
}
else
{
printf("returned a valid index which is less than or equal to mini which is btw %d\n",ret);
if(breaaking[ret]==mini)
{
printf("mini was equal to one of the element of array hence\n");
printf("No\n");
}
else
{ printf("mini is smaller than this element but greater than next element\n");
if(breaaking[ret+1]<maxi)
{
printf("next element lies between mini and maxi hence:\n") ;
printf("No\n");
}
else
{ printf("even maxi is smaller than next element hence\n");
printf("Yes\n");
}
}
`}
答案 0 :(得分:1)
您只需使用std::lower_bound
即可返回包含所有值的范围。如果没有,范围将为空。
#include <iostream>
#include <algorithm>
#include <tuple>
template<typename ForwardIterator>
std::pair<ForwardIterator, ForwardIterator>
range_inside(ForwardIterator b, ForwardIterator end,
int lower, int upper) {
auto it = std::lower_bound(b, end, lower);
auto it2 = std::upper_bound(it, end, upper);
return std::make_pair(it, it2);
}
int main()
{
int arr[] = { 2, 5, 9, 10, 11, 15};
int *r, *e;
std::tie(r, e) = range_inside(std::begin(arr), std::end(arr), 2, 10);
std::for_each(r, e, [] (int& x) { std::cout << x << " "; });
// output: 2 5 9
return 0;
}