Search code examples
algorithmoverflowbinary-search

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.


Solution

  • 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.