The following is the pseudocode I got from a TopCoder tutorial about binary search
binary_search(A, target):
lo = 1, hi = size(A)
while lo <= hi:
It is indeed possible for (hi+lo)
to overflow integer. In the improved version, it may seem that subtracting lo from hi and then adding it again is pointless, but there is a reason: performing this operation will not overflow integer and it will result in a number with the same parity as hi+lo
, so that the remainder of (hi+lo)/2
will be the same as (hi-lo)/2
. lo can then be safely added after the division to reach the same result.