Generate Permutations algorithm

I have a code that generate permutations of n elements. I need a step by step commentation for this code. Can someone help me with this and tell me what kind of algorithm it is? Thank you very much!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;

double tstart, tstop, ttime;




/**
   Read a number, N, from standard input and print the
   permutations.
 */

void print(const int *v, const int size)
{
	 
  if (v != 0) {
    for (int i = 0; i < size; i++) {
      printf("%4d", v[i] );
    }
    printf("\n");
  }
} // print


void swap(int *v, const int i, const int j)
{
  int t;
  t = v[i];
  v[i] = v[j];
  v[j] = t;
} 


void rotateLeft(int *v, const int start, const int n)
{
  int tmp = v[start];
  for (int i = start; i < n-1; i++) {
    v[i] = v[i+1];
  }
  v[n-1] = tmp;
} // rotateLeft


void permute(int *v, const int start, const int n)
{
  print(v, n);
  if (start < n) {
    int i, j;
    for (i = n-2; i >= start; i--) {
      for (j = i + 1; j < n; j++) {
	swap(v, i, j);
	permute(v, i+1, n);
      } // for j
      rotateLeft(v, i, n);
    } // for i
  }
} // permute


void init(int *v, int N)
{
  for (int i = 0; i < N; i++) {
    v[i] = i+1;
  }
} // init


void
main()
{
	 
  char buf[80];
  int N;
  printf("Enter the number of elements: ");
  fgets(buf, sizeof(buf), stdin );
  sscanf(buf, "%d", &N);
  tstart = (double)clock()/CLOCKS_PER_SEC;

  if (N > 0 && N <= 11) {
    int *v = new int[N];
    init(v, N);
    permute(v, 0, N);
    delete [] v;

	tstop = (double)clock()/CLOCKS_PER_SEC;

    ttime= tstop-tstart; /*ttime is how long your code run*/
	cout << " Took "<< tstop-tstart << " seconds to compute." << 
		endl;
	



}
  
  }
    


Topic archived. No new replies allowed.