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.
SyntaxParameterfirst: 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 valueIt returns true if an element equivalent to val is found otherwise, it returns false. ComplexityOn average, complexity is logarithmic in the distance between first and last: performs up to log2 (N) + 2 element comparisons Where N = last - first. Data racesThe object in the range [first, last) are accessed. ExceptionsThis 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 1Let's see the simple example to demonstrate the use of binary_search(): Output: 4 found Example 2Let's see another simple example: Output: looking for a 3... found! looking for a 6... not found. Example 3Let'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 4Let'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 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India