[英]Why this binary search implementation causes overflow
In the implementation of binary search二分查找的实现
int search(int[] A, int K) {
int l = 0;
int u = A.length - 1;
int m
while ( l <= u ) {
m = (l+u)/2; // why this can cause overflow
...
}
}
The correct method is as follows:正确的方法如下:
m = l + (u -l )/2;
I don't know why the updated statement has no overflow issue.我不知道为什么更新后的语句没有溢出问题。 Based on my understanding, soon or later, the updated statement will also have overflow issue.
根据我的理解,更新的语句迟早也会有溢出的问题。
Thank you谢谢
The orignal may have overflow because l+u
could be greater than the maximum value an int
can handle (eg if both l
and u
were INT_MAX
then their sum would obviously exceed INT_MAX
).由于
l+u
可能大于int
可以处理的最大值(例如,如果l
和u
都是INT_MAX
那么它们的总和显然会超过INT_MAX
), INT_MAX
值可能会INT_MAX
。
The correct method can't overflow, because ul
obviously won't overflow, and l+(ul)/2
is guaranteed to be <=u
, so can't overflow either.正确的方法不能溢出,因为
ul
显然不会溢出,而l+(ul)/2
保证是<=u
,所以也不能溢出。
The initial Calculation of m = (l+u)/2
create overflow due to addition of very large numbers .由于添加了非常大的数字,
m = (l+u)/2
的初始计算会产生溢出。 So , Difference of these numbers does not cause this overflow condition ,that's why we are calculating m=l+(ul)/2
using this formula .所以,这些数字的差异不会导致这种溢出情况,这就是我们使用这个公式计算
m=l+(ul)/2
原因。 Hope you got your answer希望你得到你的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.