Rogue Wave banner
Previous fileTop of documentContentsIndexNext file

14.5 Binary Search

The Standard C++ Library provides a number of different variations on binary search algorithms. All perform only approximately log n comparisons, where n is the number of elements in the range described by the arguments. The algorithms work best with random access iterators, like those generated by vectors or deques, when they also perform approximately log n operations in total. However, they also work with non-random access iterators, like those generated by lists, in which case they perform a linear number of steps. Although legal, it is not necessary to perform a binary search on a set or multiset data structure, since those container classes provide their own search methods, which are more efficient.

The generic algorithm binary_search() returns true if the sequence contains a value that is equivalent to the argument. Recall that to be equivalent means that both Compare(value, arg) and Compare(arg, value) are false. The algorithm is declared as follows:

In other situations it is important to know the position of the matching value. This information is returned by a collection of algorithms, defined as follows:

The algorithm lower_bound() returns, as an iterator, the first position into which the argument could be inserted without violating the ordering, whereas the algorithm upper_bound() finds the last such position. These match only when the element is not currently found in the sequence. Both can be executed together in the algorithm equal_range(), which returns a pair of iterators.

Our example program shows these functions being used with a vector of random integers.


Previous fileTop of documentContentsIndexNext file
©Copyright 1998, Rogue Wave Software, Inc.
Send mail to report errors or comment on the documentation.
OEM Release, June 1998