Generating Permutations in C++

#include <vector>
#include <iostream>

using namespace std;

void reverse(vector<int> &seq,int n1,int n2) {

  for(;(n2-n1)>=1;) {
    int temp = seq[n1]; seq[n1] = seq[n2]; seq[n2]=temp;
    n1++;
    n2--;
  }

}

int main() {

  int seq_len=4;

  vector<int> seq;
  for(int n=0;n<seq_len;n++) {seq.push_back(n);}
  for(int n=0;n<seq.size();n++) cout << seq[n] << " ";
  cout << endl;

  for(int n=0;n<seq_len;n++) {

    for(bool final=false;final==false;) {

      final=true;
      int k=0;

      for(int n=0;n<(seq.size()-1);n++) {
        if(seq[n] < seq[n+1]) {k=n; final=false;}
      }

      if(!final) {
        int l;
        for(int n=k+1;n<seq.size();n++) {
          if(seq[k] < seq[n]) {
            l=n;
          }
        }

        int temp = seq[k]; seq[k] = seq[l]; seq[l] = temp;
        reverse(seq,k+1,seq.size()-1);
        for(int n=0;n<seq.size();n++) cout << seq[n] << " ";
        cout << endl;
      }
    }
  }
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>