Binary Search
Find something among a million sorted items in about twenty looks, by throwing away half of what is left every time.
After this lesson you will be able to
- Explain why sorted data lets you discard half the candidates with one comparison.
- Write a correct
lower_boundwith a clear invariant, and avoid infinite loops and off-by-one errors. - Use lower and upper bound to count occurrences and find insertion points.
- Apply “binary search on the answer” to minimise or maximise a value that can be checked.
- Recognise monotonic yes/no structure in a problem statement.
Before you start. You should know how to sort a list and index into it. Sorting Basics covers what “sorted” gives you.