gotchaMajor
Why is binary search using this weird thing to calculate middle?
Viewed 0 times
thiswhysearchweirdbinaryusingcalculatemiddlething
Problem
I noticed that in many books calculation of midpoint for binary search uses this:
Why not use
instead?
int mid = left + (right - left) / 2;Why not use
int mid = (left + right) / 2;instead?
Solution
Because
So instead they take the distance between
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.