-
Notifications
You must be signed in to change notification settings - Fork 362
/
heaps_algorithm.hpp
61 lines (45 loc) · 2.01 KB
/
heaps_algorithm.hpp
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
/*
Heap's Algorithm
----------------
This algorithm generates all possible permutations of a collection of n elements.
The algorithm minimizes movement: it generates each permutation from the previous
one by interchanging a single pair of elements, while the other n-2 remain undisturbed.
Time Complexity
---------------
O(N!), where N is the number of elements in the collection
Space Complexity
----------------
O(N), where N is the number of elements in the collection
*/
#ifndef HEAPS_ALGORITHM_HPP
#define HEAPS_ALGORITHM_HPP
#include <vector>
using std::string;
using std::vector;
using std::swap;
vector<string> heaps_algorithm(unsigned int number_of_elements, string& collection, vector<string>& permutations) {
if (number_of_elements == 1 || collection.empty()) {
permutations.push_back(collection);
}
else {
/* Generate permutations with i-th element unaltered
* Initially number_of_elements == length of input string */
heaps_algorithm(number_of_elements - 1, collection, permutations);
/* Generate permutations where the i-th element is swapped
* with each i-1 initial elements */
for (unsigned int i = 0; i < number_of_elements - 1; i++) {
/* The swap choice depends on the parity of
* number_of_elements within each recursive call */
if (number_of_elements % 2 == 0) {
swap(collection[i], collection[number_of_elements - 1]); // zero-indexed, the i-th is at i-1
} else {
swap(collection[0], collection[number_of_elements - 1]);
}
/* This second recursive call exists to avoid additional swaps at each level
* The algorithm would work without it, but wouldn't be the way B.R. Heap designed it */
heaps_algorithm(number_of_elements - 1, collection, permutations);
}
}
return permutations;
}
#endif //HEAPS_ALGORITHM_HPP