![]() |
VOOZH | about |
Heap's algorithm is used to generate all permutations of n objects. The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements.
Following is the illustration of generating all the permutations of n given numbers.
Example:
Input: 1 2 3 Output: 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1
Algorithm:
Implementation:
1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1
Time Complexity: O(N*N!), where N is the size of the given array.
Auxiliary Space: O(N), for recursive stack space of size N.
References:
1. "https://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3