加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用迭代器的二进制搜索,为什么我们使用“(end-begin)/ 2”

发布时间:2020-12-16 10:03:32 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why prefer start + (end – start) / 2 over (start + end) / 2 when calculating the middle of an array?????????????????????????????????????3个 我正在研究迭代器,并且已经停留3天了解我们为什么要使用: auto mid = text.begin() + (end
参见英文答案 > Why prefer start + (end – start) / 2 over (start + end) / 2 when calculating the middle of an array?????????????????????????????????????3个
我正在研究迭代器,并且已经停留3天了解我们为什么要使用:

auto mid = text.begin() + (end - beg) / 2;

码:

int main()

{
    vector<int> text{ 10,9,8,7,6,5,4,3,2,1 };
    int sought = 3;
    // text must be sorted
    // beg and end will denote the range we're searching
    auto beg = text.begin(),end = text.end();
    auto mid = text.begin() + (end - beg) / 2; // original midpoint
                                               // while there are still elements to look at and we haven't yet found sought
    while (mid != end && *mid != sought) {
        if (sought < *mid) // is the element we want in the first half?
            end = mid; // if so,adjust the range to ignore the second half
        else // the element we want is in the second half
            beg = mid + 1; // start looking with the element just after mid
        mid = beg + (end - beg) / 2;// new midpoint
    }

    system("pause");
}

为什么

auto mid = text.begin() + (end - beg) / 2;

并不是:

auto mid = text.begin() + text.size() / 2;

请帮忙.

解决方法

这样做是为了避免在添加两个非常大的整数时可能发生的溢出,其中加法结果可能变得大于最大整数限制并产生奇怪的结果.

Extra,Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken

来自博客:

So what's the best way to fix the bug? Here's one way:
 6:             int mid = low + ((high - low) / 2);

Probably faster,and arguably as clear is:
 6:             int mid = (low + high) >>> 1;

In C and C++ (where you don't have the >>> operator),you can do this:
 6:             mid = ((unsigned int)low + (unsigned int)high)) >> 1;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读