参见英文答案 >
Why prefer start + (end – start) / 2 over (start + end) / 2 when calculating the middle of an array? 3个
我正在研究迭代器,并且已经停留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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。