How to set the middle value in a binary search?
1 min readJul 28, 2020
Binary search the idea is simple, however, if we are not careful about the setting of the middle value, we may get TLE.
Some binary search problems can be found in my previous article HERE.
The trick that we can use to set the middle value is:
- if the updating process is , left = mid, set the mid = (left + right + 1)/2
- if the updating process is , left = mid + 1, set the mid = (left + right )/2
In order to avoid overflow(for left + right operation), in C++, we also using this way:
- if the updating process is , left = mid, set the mid = left + (right -left + 1)/2
- if the updating process is , left = mid + 1, set the mid = left + ( right — left)/2
Thanks for reading and hope it is helpful.