# Why is binary search using this weird thing to calculate middle?

I noticed that in many books calculation of midpoint for binary search uses this:

int mid = left + (right - left) / 2;


Why not use

int mid = (left + right) / 2;


• The only "advantage" is that your calculation never exceeds the value of right. – fade2black Aug 25 '17 at 10:42
• @fade2black, I don't see how is it possible to exceed value of right in second case. If left = right, then (2 * right) / 2 = right. – rus9384 Aug 25 '17 at 10:45
• @rus9384 left + right >= right, intermediate values I mean. Kind of take actions against overflow. – fade2black Aug 25 '17 at 10:47
• @fade2black, I think, this is an answer. – rus9384 Aug 25 '17 at 10:52
• This is indeed the answer. – Raphael Aug 25 '17 at 11:15

Because left + right may overflow. Which then means you get a result that is less than left. Or far into the negative if you are using signed integers.
So instead they take the distance between left and right and add half of that to left. This is only a single extra operation to make the algorithm more robust.