This article Senlie original, reproduced please retain this address:Http://blog.csdn.net/zhengsenlie
Pre_permutation
----------------------------------------------------------------
Descriptive narrative: The previous permutation of the sequence marked by [first, last].
Assume no, return false, have, return true
Ideas:
From the back forward
1. Find two adjacent elements, so that the left side of the element is *i, the right side of the element is *ii, and meet *i > *ii
2. Find the first element that is less than *i and make it *j. Swap the *I,*J elements
3. Invert all elements in the right side of II
Template <class Bidirectionaliterator>bool prev_permutation (bidirectionaliterator first, Bidirectionaliterator last) { if (first = = last) return false; Bidirectionaliterator i = first; ++i; if (i = = last) return false; i = last; I.; for (;;) { Bidirectionaliterator II = i; I.; if (*ii < *i) { //Meet *ii < *i-Next_permutation condition is *i < *ii Bidirectionaliterator j = Last;
while (! ( *--j < *i)); Find the *j to meet *j < *i when the condition is *i < *j Iter_swap (i, j); Reverse (ii, last); return true; } if (i = = first) { reverse (first, last) ; return false;}} }
Demo Sample:
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<int> (cout, "")); cout << Endl; Prev_permutation (A, a+n); cout << "after Prev_permutation:"; Copy (A, A+n, ostream_iterator<int> (cout, "")); cout << Endl; Next_permutation (A, a+n); cout << "after Next_permutation:"; Copy (A, A+n, ostream_iterator<int> (cout, "")); cout << Endl;}
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
STL Source Code Analysis algorithm Stl_algo.h--pre_permutation