STL Source Code Analysis algorithm Stl_algo.h--pre_permutation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.