STL source code profiling algorithm stl_algo.h -- pre_permutation
Pre_permutation
----------------------------------------------------------------
Description: gets the first permutation and combination of the sequence marked by [first, last. If no value exists, false is returned. If yes, true is returned.
Ideas:
From the back to the front
1. Find two adjacent elements, set the left-side element to * I, and the right-side element to * ii, which meets * I> * ii
2. Find the first element smaller than * I and set it to * j. The * I and * j elements are reversed.
3. Reverse all elements on the right side of ii
Template
Bool prev_permutation (BidirectionalIterator first, BidirectionalIterator last) {if (first = last) return false; bidirealialiterator I = first; ++ I; if (I = last) return false; I = last; -- I; for (;) {BidirectionalIterator ii = I; -- I; if (* ii <* I) {// The condition for meeting * ii <* I --> next_permutation is * I <* ii BidirectionalIterator j = last; while (! (* -- J <* I); // when finding the * j <* I * j --> next_permutation, the condition is * I <* j iter_swap (I, j); reverse (ii, last); return true;} if (I = first) {reverse (first, last); return false ;}}}
Example:
int main(){ int A[] = {2, 3, 4, 5, 6, 1}; const int N = sizeof(A) / sizeof(int); cout << Initially: ; copy(A, A+N, ostream_iterator
(cout, )); cout << endl; prev_permutation(A, A+N); cout << After prev_permutation: ; copy(A, A+N, ostream_iterator
(cout, )); cout << endl; next_permutation(A, A+N); cout << After next_permutation: ; copy(A, A+N, ostream_iterator
(cout, )); cout << endl;}