简体   繁体   中英

Time complexity of `std::partition()`

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM