I've written binary search recursively with my own effort . While calculating middle index, I did int mid = (low + high) / 2
. I googled recursive version of binary search and found that the calculation is a bug. Because it may overflow if (low + high)
is greater than maximum value of integer. Two types solutions there are.
int mid = low + (high - low) / 2
int mid = (high + low) >>> 1
(unsigned right shift, it does division by 2)
Both of them work like a charm. However, I wonder for first one how it works. Yes, it works but what the logic that the people think to find it is. For the second, how it works. Isn't there possibility to overflow for (high + low)
still? I mean my attempt is called as buggy because of overflow but the second one also does (high + low)
.