-3

What is the complexity of the std::lower_bound and std::upper_bound functions.

I know in case of std::set<int> it is log(n), but I have no idea for a std::vector<int>.

I was going through an implementation of the Longest Increasing Subsequence using vectors and std::lower_bound.

What is the complexity of this code?

int LIS2(vector<int> a) {
    vector<int> v;
    for (int i = 0; i < a.size(); i++) {
        auto it = lower_bound(v.begin(), v.end(), a[i]);
        if (it != v.end()) 
            *it = a[i];
        else 
            v.push_back(a[i]);
    }
    return v.size();
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

1 Answers1

5

From https://en.cppreference.com/w/cpp/algorithm/lower_bound:

Complexity

The number of comparisons performed is logarithmic in the distance between first and last (At most log2(last - first) + O(1) comparisons). However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear.

For random access iterators (e.g from std::vector) the bounds functions simply do a binary search.

For non-random access iterators (e.g. from std::list and std::set) the functions still perform a binary search but there is an additional cost as they have to increment the iterators one element at a time to move between elements.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • binary search got just `O(log n)` in worst case – Swift - Friday Pie Mar 18 '20 at 06:18
  • 1
    According to [Wikipedia](https://en.m.wikipedia.org/wiki/Binary_search_algorithm) `log2(n) +1` comparisons is correct (see the `performance` section), that is the exact complexity of the algorithm. The big O notation is an approximation (i think?) `log2(n)+1` is of the same order as `log(n)` – Alan Birtles Mar 18 '20 at 06:31
  • true, the algorithms runs in logarithmic time, but that's iterations counts, not comparison. The space complexity is still considered space complexity of binary search is `O(log n)`. Suppose that `O(1)` may account for it. To e honest I though you meant power of two with that space after `log`, which would be sorting complexity or roughly complexity of bound function run on a list or set – Swift - Friday Pie Mar 18 '20 at 07:19
  • the text of the quote is just copied from the link – Alan Birtles Mar 18 '20 at 07:22