C++ Algorithm binary_search()

C++ Algorithm binary_search() function is used check whether the element in the range [first, last) is equivalent to val (or a binary predicate) and false otherwise.

  • The range [first, last) must satisfy all of the following conditions:
    • Partitioned with respect to element < val or comp (element, val).
    • Partitioned with respect to !(val < element) or !comp(value, element)
    • For all elements, if element < val or comp (element, val) is true then !(val < element) or !comp(val, element) is also true.
  • The first version uses operator< to compare the elements and the second version uses the given comparison function i.e. comp.

Syntax

Parameter

first: A forward iterator pointing to the first element in the range to be searched.

last: A forward iterator pointing to the past last element in the range to be searched.

comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise. It follows the strict weak ordering to order the elements.

val: A value of the upper bound to compare the elements in the range.

Return value

It returns true if an element equivalent to val is found otherwise, it returns false.

Complexity

On average, complexity is logarithmic in the distance between first and last: performs up to log2 (N) + 2 element comparisons Where N = last - first.

Data races

The object in the range [first, last) are accessed.

Exceptions

This function throws an exception if either an element comparison or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of binary_search():

Output:

4 found

Example 2

Let's see another simple example:

Output:

looking for a 3... found!
looking for a 6... not found.

Example 3

Let's see another simple example to compare the elements using comparison function:

Output:

Here are the values in the vector:
1 2 3 4 5 6 7 9 10 
The value 3 was found.
The value 8 was not found.

Example 4

Let's see another simple example:

Output:

Sorted vector elements : 1 2 3 4 5 6 7 8 9 
Searching for 4 : found!
Searching for element greater than 9 : not found.

Next TopicC++ Algorithm




Latest Courses