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.
The orignal may have overflow because
l+ucould be greater than the maximum value anintcan handle (e.g. if bothlanduwereINT_MAXthen their sum would obviously exceedINT_MAX).The correct method can’t overflow, because
u-lobviously won’t overflow, andl+(u-l)/2is guaranteed to be<=u, so can’t overflow either.