![]() |
VOOZH | about |
Binary search functions in C++ STL provide an efficient way to search and locate elements in sorted containers. These functions use the binary search algorithm internally and perform operations in O(log n) time complexity.
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: Program to show how to use the binary_search() for searching an element in the given range
15 exists in vector 23 does not exist
Explanation
Time Complexity: O(log n), where n is the number of elements.
Auxiliary Space: O(1)
The std::lower_bound function returns an iterator to the first element in a sorted range that is greater than or equal to the specified value. It is commonly used to find the position of an element or the correct insertion point while maintaining sorted order.
Syntax:
lower_bound(start, end, val);
2 2 2
Explanation
Time Complexity: O(log n), Where n is the number of elements.
Auxiliary Space: O(1)
The std::upper_bound function returns an iterator to the first element in a sorted range that is strictly greater than the specified value. It is commonly used to find the position immediately after the last occurrence of a value in a sorted container.
Syntax:
upper_bound(start, end, val);
3 4 2
Explanation
Time Complexity: O(log n), Where n is the number of element
Auxiliary Space: O(1)