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
).
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.
The initial Calculation of m = (l+u)/2
create overflow due to addition of very large numbers . So , Difference of these numbers does not cause this overflow condition ,that's why we are calculating m=l+(ul)/2
using this formula . Hope you got your answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.