VOOZH about

URL: https://www.geeksforgeeks.org/dsa/heaps-algorithm-for-generating-permutations/

⇱ Heap's Algorithm for generating permutations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Heap's Algorithm for generating permutations

Last Updated : 14 Dec, 2022

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: 

  1. The algorithm generates (n-1)! permutations of the first n-1 elements, adjoining the last element to each of these. This will generate all of the permutations that end with the last element.
  2. If n is odd, swap the first and last element and if n is even, then swap the ith element (i is the counter starting from 0) and the last element and repeat the above algorithm till i is less than n.
  3. In each iteration, the algorithm will produce all the permutations that end with the current last element.

Implementation:  


Output
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

Comment
Article Tags:
Article Tags: