HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaMajor

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

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
thiswhysearchweirdbinaryusingcalculatemiddlething

Problem

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;


instead?

Solution

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.

Context

StackExchange Computer Science Q#80415, answer score: 22

Revisions (0)

No revisions yet.