the highest index of a binary search

left + (right - left) / 2

is the same as

(right + left) / 2

They both take the average of right and left. The purpose of using the former one is to prevent integer overflows. If right + left is bigger than the variable can carry, even though this variable can carry their average, the result will be wrong, because right + left will cause overflow.

On the other hand, first calculating (right - left) / 2 and adding left prevents overflow.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top