Binary search is a workhorse of competitive programming. There are
occasional easy problems where binary search is the solution in and
of itself; more often, it’s used as a primitive building block of
more complex algorithms. It is often presented as a way to find the
index of something in a sorted array in O(lg n) time, and many
languages have such a thing in their standard library (for example,
see Arrays.binarySearch in
Java,
the bisect library in
Python, or the
binary_search function in
C++). However,
the idea of binary search is more general than searching in a sorted
array; we’re doing binary search any time we repeatedly halve a
search interval. For example, we can use it to find the smallest or
largest number with a given property, or to find an optimal, “just
right” measurement that is neither too small nor too big.