![]() |
VOOZH | about |
The std::upper_bound() and std::lower_bound() perform binary search on random-access STL containers and are defined in <algorithm>. Here, we focus on their use with vectors in C++ STL.
The std::lower_bound() method can be used to find the first value that is greater than or equal to given value in the vector. It needs the vector to be sorted because it implements binary search to find the value.
30
The std::upper_bound() method can be used to find the first value that is greater than to given value in the vector. It needs sorted vector because it implements binary search to find the value.
40
Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)
The below examples demonstrate the use of std::upper_bound and std::lower_bound in a vector in different scenarios
34 56
Time Complexity: O(log n), not considering time required for sorting.
Auxiliary Space: O(1), not considering memory required for sorting.
Explanation: As we know that std::upper_bound() and std::lower_bound() doesn't works for unsorted vector, so we use std::sort() function to sort the vector. After that, we find the lower and upper bound in the desired range.
56 is found.
Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)
Explanation
No. of Smaller Elements: 2 No. of Larger Elements: 3
Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)
Explanation
ower_bound() returns an iterator to the first element ≥ the given value in a sorted vector.v.begin() from it gives their count.