简体   繁体   English

C ++二进制搜索,如lower_bound

[英]C++ Binary search like lower_bound

I do have problem with my binary search which should work a little like lower_bound. 我的二进制搜索确实有问题,它应该像Lower_bound一样工作。 This gives me a segfault in 5th run. 这使我在第5次跑步中遇到了段错误。 Can anyone see a problem ? 有人可以看到问题吗? Thanks 谢谢

int BinarySearch ( const char * a, int firstindex , int lastindex){
    if (m_len == 0) return 0; //number of items in searched array
    if ( firstindex == lastindex ) return lastindex;
    int tmp = lastindex - firstindex;
    int pos = tmp/2;
    if ( tmp % 2 != 0 ) ++pos;
    if (strcmp(a,Arr[pos]) < 0) return BinarySearch(a,firstindex,pos-1);
    if (strcmp(a,name) > 0) return BinarySearch(a,pos+1,lastindex);
    return pos;
}

int tmp = lastindex - firstindex;

Should be: 应该:

int tmp = lastindex + firstindex;

That is because you are looking for the middle of the indexes x and y which is (x+y)/2. 这是因为您正在寻找索引x和y的中间值,即(x + y)/ 2。

Your code's behaviour should be unpredictable, possibly looping and causing segmentation fault. 您的代码的行为应不可预测,可能会循环并导致分段错误。

The midpoint between x and y is x + (y - x)/2, so you want x和y之间的中点是x +(y-x)/ 2,所以你想

int pos = firstIndex + tmp/2;

Using the slightly more complex expression instead of the obvious (x + y)/2 eliminates an overflow bug that is very common. 使用稍微复杂些的表达式而不是明显的(x + y)/ 2可以消除非常常见的溢出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM