Binary search is not so much an algorithm as a way of thinking.
Core code
| |
Advantages
It brings an ordinary search down from O(n) to O(log n).
Requirements
The data you search must be sorted.
Explanation
Binary search shrinks the range in which the answer can lie, again and again, until the optimum is found. In coursework and in contests you will often meet problems that combine binary thinking with some other algorithm.
Uses
Finding a value in a sorted array
Binary search can answer, for a given array,
- whether a value exists
- where that value sits
Solving an equation within a tolerance
Halve the interval over and over until the solution is precise enough.
Maximising the minimum
Minimising the average
Problems of this shape are easy to compare because you can tell whether a candidate is above or below the real answer. So even without knowing what the answer is, you can shrink its range by comparison.
Reference:
Programming Contest Challenge Book
Baidu Baike