3 years ago
(start + end) // 2 for calculating mid. There is a chance for overflow (not in Python) but this works all the time. Remember, if you're using this, your while loop needs to be start <= endstart + (end - start + 1) // 2, where your while loop becomes start < endSuppose we have a search space. It could be an array, a range, etc. Usually it's sorted in ascend order. For most tasks, we can transform the requirement into the following generalized form:
Minimize k , s.t. condition(k) is True
The following code is the most generalized binary search template:
What's really nice of this template is that, for most of the binary search problems, we only need to modify three parts after copy-pasting this template, and never need to worry about corner cases and bugs in code any more:
left and right. Only one rule: set up the boundary to include all possible elements;return left or return left - 1? Remember this: after exiting the while loop, left is the minimal k satisfying the condition function;condition function. This is the most difficult and most beautiful part. Needs lots of practice.