开发者

Why this binary search implementation causes overflow?

开发者 https://www.devze.com 2023-02-05 21:14 出处:网络
In the implementation of binary search int search(int[] A, int K) { int l = 0; int u = A.length - 1; int m

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+u could be greater than the maximum value an int can handle (e.g. if both l and u were INT_MAX then their sum would obviously exceed INT_MAX).

The correct method can't overflow, because u-l obviously won't overflow, and l+(u-l)/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+(u-l)/2 using this formula.

0

精彩评论

暂无评论...
验证码 换一张
取 消