Tuesday, September 25, 2012

C++ next_permutation implementation

template<typename Iter>
bool next_permutation(Iter first, Iter last) {
    // Empty
    if (first == last) return false;
    Iter i = first;
    ++i;
    // Only one element
    if (i == last) return false;
    i = last;
    --i;
       
    for(;;) {
        Iter ii = i;
        --i;
        // Check if there are two adjacent elements
        // such that the first one is smaller than the second one
        if (*i < *ii) {
            Iter j = last;
            // Find the first element that are bigger than i
            while (!(*i < *--j)) {}
            std::iter_swap(i, j);
            // Reverse the decreasing sequence
            std::reverse(ii, last);
            return true;
        }
        // No, this is the last permutation
        if (i == first) {
            std::reverse(first, last);
            return false;
        }
    }
}

No comments:

Post a Comment