Open In App

Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
94 Likes
Like
Report

In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data.

There are the 3 binary search function in C++ STL:

binary_search()

The std::binary_search() function is used to find an element in the container. It will only work on the sorted data. It will take logarithmic time to search an element from the container as it implementing the binary search algorithm internally.

Syntax

binary_search(start, end, val);

Example


Output
15 exists in vector
23 does not exist

Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)

lower_bound()

The std::lower_bound is used to find first element in the given range that is greater than or equal to the given value.

Syntax

lower_bound(start, end, val);

Example


Output
2
2
2

Time Complexity: O(log n), Where n is the number of elements.
Auxiliary Space: O(1)

upper_bound()

The std::upper_bound is used to find first element in the given range that is greater than the given value.

Syntax

upper_bound(start, end, val);

Example


Output
3
4
2

Time Complexity: O(log n), Where n is the number of element
Auxiliary Space: O(1)


Next Article

Similar Reads