Binary search finds a target in a sorted range by repeatedly comparing it with the middle element and discarding the half that cannot contain it. It runs in O(log n) time and needs random access, so it works on arrays and std::vector but not on linked lists. In C++ you can write it by hand or call std::binary_search, std::lower_bound and std::ranges::equal_range.
The range must already be sorted with the same ordering you search with, or the result is undefined.
Keep two bounds, lo and hi, around the part of the array that might hold the target. Compare the middle element with the target:
lo past the middle.hi to the middle.Each step halves the range, so 1,000,000 elements need at most about 20 comparisons. A linear scan would need up to 1,000,000.
The version below uses a half-open range [lo, hi), which avoids most off-by-one mistakes, and returns std::optional instead of a magic value such as -1. It takes a std::span, so it accepts a vector, an array or any contiguous range.
Compile with g++ -std=c++20 -O2 bs.cpp -o bs. Output:
The textbook (lo + hi) / 2 can overflow when the indices are large, which was a real bug in widely used library code for years. Writing lo + (hi - lo) / 2 is always safe. C++20 also provides std::midpoint in <numeric> for the same purpose.
Prefer the standard algorithms in production code. They are tested, work with any ordering and handle duplicates in well-defined ways.
| Function | Returns | Use it when |
|---|---|---|
std::binary_search | bool | You only need to know whether the value exists |
std::lower_bound | Iterator to the first element not less than the value | You need the position or an insertion point |
std::upper_bound | Iterator to the first element greater than the value | You need the end of a run of equal values |
std::equal_range | Pair of iterators [lower, upper) | You need all matching elements or their count |
C++20 adds range versions in std::ranges, for example std::ranges::binary_search(v, 56) and std::ranges::equal_range(v, 16), which take the container directly and support projections. All of them require a sorted range and run in logarithmic time for random access iterators.
| Case | Time | Extra space |
|---|---|---|
| Iterative binary search | O(log n) | O(1) |
| Recursive binary search | O(log n) | O(log n) call stack |
| Linear search | O(n) | O(1) |
Binary search only pays off on sorted data. If you search once in unsorted data, a linear scan is cheaper than sorting first. If you search many times, sort once and then search. For very small arrays, a linear scan can be faster in practice because of cache behaviour and branch prediction. For keyed lookups that change often, std::unordered_map or std::map fits better than keeping a sorted vector.
[lo, hi] with a mixed hi = mid update, which can loop forever.(lo + hi) / 2 on large indices.hi = mid - 1 when mid is 0.lower_bound and a tolerance check instead.It is O(log n) for random access ranges and uses O(1) extra space when written iteratively.
Not efficiently. It needs constant-time access to the middle element. std::list iterators are bidirectional, so each jump costs O(n) and the algorithm loses its advantage.
Use std::lower_bound for the first occurrence and std::upper_bound for the position after the last one. std::equal_range returns both at once.
Rarely. Use the standard algorithms unless you need a custom search condition, such as searching on a monotonic predicate, where writing the loop yourself is reasonable.
Binary search halves a sorted range at every step and takes O(log n) time. Use a half-open range, compute the midpoint without overflow and return std::optional rather than a sentinel. In everyday C++ code, call std::binary_search, std::lower_bound or the std::ranges versions instead of writing the loop yourself.