-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpermutation.cpp
87 lines (72 loc) · 1.4 KB
/
permutation.cpp
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
/*
* Copyright 2010, NagaChaitanya Vellanki
*
* Author NagaChaitanya Vellanki
*
*/
#include <iostream>
#include <stdint.h>
#include <vector>
#include <algorithm>
using namespace std;
void PrintArray(vector<int32_t> &array)
{
for (int32_t index = 0; index < array.size(); index++)
{
cout << array[index] << " ";
}
cout << endl;
}
/*
*Generate Lexiographic permutation of a given array of sorted elements
* Refer to The Art of Computer Programming, Volume 4, Fascicle 2
*
*/
void Permutation(vector<int32_t> &array, int32_t n) {
while(true) {
PrintArray(array);
int32_t j = n - 1;
// Find j
while(array[j] >= array[j + 1]) {
if(j == 0) return;
j--;
}
// Increase aj
int32_t l = n;
while(array[j] >= array[l]) {
if(l > 0) {
l--;
} else {
break;
}
}
// swap aj, al
swap(array[j], array[l]);
// Reverse aj+1 ... an
int32_t k = j + 1;
l = n;
while(k < l) {
swap(array[k],array[l]);
k++;
l--;
}
}
}
int main()
{
int32_t n = 0;
int32_t temp = 0;
vector<int32_t> array;
cout << "Enter the number of elements" << endl;
cin >> n;
// read the elements
cout << " ** Enter the elements of the array **" << endl;
for (int32_t index = 0; index < n; index++)
{
cin >> temp;
array.push_back(temp);
}
cout << endl;
Permutation(array, n - 1);
return 0;
}