Time complexity of `std::partition()`

时间:2016-02-03 03:30:46

标签: c++ algorithm c++11 time-complexity quicksort

According to cppreference:

Complexity
Exactly std::distance(first,last) applications of the predicate and at most std::distance(first,last) swaps. If ForwardIt meets the requirements of BidirectionalIterator at most std::distance(first,last)/2 swaps are done.

I looked at the sample implementation at the bottom:

template<class ForwardIt, class UnaryPredicate>
ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
    if (first == last) return first;
    ForwardIt part(first++);
    if (first == last) return p(*part) ? first : part;
    while (first != last) {
        if (p(*part))
            ++part;
        else if (p(*first)) {
            iter_swap(part, first);
            ++part;
        }
        ++first;
    }
    return part;
}

I think it performs at most std::distance(first,last)/2 swaps instead of std::distance(first,last). No?

1 个答案:

答案 0 :(得分:3)

This appears to be an implemention for non-bidirectional iterator, going forward only. Going forward only through a sequence of n items, at least n-1 swaps are needed to move a single non-p item from start to end. With bidirectional iterators one can work inwards from both ends.