0

I'm writing a binary search algorithm in which I need to calculate the mid element. There are two ways two get the middle element such as:

low+(high-low)/2

and

(low+high)/2

It seems that low+(high-low)/2 is more efficient than (low+high)/2, why?

Ryan
  • 2,825
  • 9
  • 36
  • 58
  • 3
    Please tell us how it is more efficient? – SomeDude Jul 15 '16 at 11:46
  • @svasa https://leetcode.com/problems/guess-number-higher-or-lower/ I wrote two solutions for this problem, one passes the test, the other results in exceeding time limit. – Ryan Jul 15 '16 at 11:48

1 Answers1

0

I found the answer here.

Under the assumption that high and low are both non-negative, we know for sure that the upper-most bit (the sign-bit) is zero.

So both high and low are in fact 31-bit integers.

high = 0100 0000 0000 0000 0000 0000 0000 0000 = 1073741824
low  = 0100 0000 0000 0000 0000 0000 0000 0000 = 1073741824

When you add them together they may "spill" over into the top-bit.

high + low =       1000 0000 0000 0000 0000 0000 0000 0000
           =  2147483648 as unsigned 32-bit integer
           = -2147483648 as signed   32-bit integer

(high + low) / 2   = 1100 0000 0000 0000 0000 0000 0000 0000 = -1073741824
(high + low) >>> 1 = 0100 0000 0000 0000 0000 0000 0000 0000 = 1073741824
Community
  • 1
  • 1
Ryan
  • 2,825
  • 9
  • 36
  • 58