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:
- 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.
- 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.
- In each iteration, the algorithm will produce all the permutations that end with the current last element.
Implementation:
C++
// C++ program to print all permutations using
// Heap's algorithm
#include <bits/stdc++.h>
using namespace std;
// Prints the array
void printArr(int a[], int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
printf("\n");
}
// Generating permutation using Heap Algorithm
void heapPermutation(int a[], int size, int n)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1) {
printArr(a, n);
return;
}
for (int i = 0; i < size; i++) {
heapPermutation(a, size - 1, n);
// if size is odd, swap 0th i.e (first) and
// (size-1)th i.e (last) element
if (size % 2 == 1)
swap(a[0], a[size - 1]);
// If size is even, swap ith and
// (size-1)th i.e (last) element
else
swap(a[i], a[size - 1]);
}
}
// Driver code
int main()
{
int a[] = { 1, 2, 3 };
int n = sizeof a / sizeof a[0];
heapPermutation(a, n, n);
return 0;
}
Java
// Java program to print all permutations using
// Heap's algorithm
import java.io.*;
class HeapAlgo {
// Prints the array
void printArr(int a[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
}
// Generating permutation using Heap Algorithm
void heapPermutation(int a[], int size, int n)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
printArr(a, n);
for (int i = 0; i < size; i++) {
heapPermutation(a, size - 1, n);
// if size is odd, swap 0th i.e (first) and
// (size-1)th i.e (last) element
if (size % 2 == 1) {
int temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}
// If size is even, swap ith
// and (size-1)th i.e last element
else {
int temp = a[i];
a[i] = a[size - 1];
a[size - 1] = temp;
}
}
}
// Driver code
public static void main(String args[])
{
HeapAlgo obj = new HeapAlgo();
int a[] = { 1, 2, 3 };
obj.heapPermutation(a, a.length, a.length);
}
}
// This code has been contributed by Amit Khandelwal.
Python3
# Python program to print all permutations using
# Heap's algorithm
# Generating permutation using Heap Algorithm
def heapPermutation(a, size):
# if size becomes 1 then prints the obtained
# permutation
if size == 1:
print(a)
return
for i in range(size):
heapPermutation(a, size-1)
# if size is odd, swap 0th i.e (first)
# and (size-1)th i.e (last) element
# else If size is even, swap ith
# and (size-1)th i.e (last) element
if size & 1:
a[0], a[size-1] = a[size-1], a[0]
else:
a[i], a[size-1] = a[size-1], a[i]
# Driver code
a = [1, 2, 3]
n = len(a)
heapPermutation(a, n)
# This code is contributed by ankush_953
# This code was cleaned up to by more pythonic by glubs9
C#
// C# program to print all permutations using
// Heap's algorithm
using System;
public class GFG {
// Prints the array
static void printArr(int[] a, int n)
{
for (int i = 0; i < n; i++)
Console.Write(a[i] + " ");
Console.WriteLine();
}
// Generating permutation using Heap Algorithm
static void heapPermutation(int[] a, int size, int n)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
printArr(a, n);
for (int i = 0; i < size; i++) {
heapPermutation(a, size - 1, n);
// if size is odd, swap 0th i.e (first) and
// (size-1)th i.e (last) element
if (size % 2 == 1) {
int temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}
// If size is even, swap ith and
// (size-1)th i.e (last) element
else {
int temp = a[i];
a[i] = a[size - 1];
a[size - 1] = temp;
}
}
}
// Driver code
public static void Main()
{
int[] a = { 1, 2, 3 };
heapPermutation(a, a.Length, a.Length);
}
}
/* This Java code is contributed by 29AjayKumar*/
JavaScript
<script>
// JavaScript program to print all permutations using
// Heap's algorithm
// Prints the array
function printArr(a,n)
{
document.write(a.join(" ")+"<br>");
}
// Generating permutation using Heap Algorithm
function heapPermutation(a,size,n)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
printArr(a, n);
for (let i = 0; i < size; i++) {
heapPermutation(a, size - 1, n);
// if size is odd, swap 0th i.e (first) and
// (size-1)th i.e (last) element
if (size % 2 == 1) {
let temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}
// If size is even, swap ith
// and (size-1)th i.e last element
else {
let temp = a[i];
a[i] = a[size - 1];
a[size - 1] = temp;
}
}
}
// Driver code
let a=[1, 2, 3];
heapPermutation(a, a.length, a.length);
// This code is contributed by rag2127
</script>
Output1 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
Similar Reads
Generate all permutation of a set in Python Generating all permutations of a set in Python involves creating every possible ordered arrangement of its elements. Since sets are unordered collections, the first step is usually converting the set to a list to maintain a consistent order. For example, given the set {1, 2, 3}, the permutations inc
3 min read
Different Ways to Generate Permutations of an Array Permutations are like the magic wand of combinatorics, allowing us to explore the countless ways elements can be rearranged within an array. Whether you're a coder, a math enthusiast, or someone on a quest to solve a complex problem, understanding how to generate all permutations of an array is a va
6 min read
All permutations of a string using iteration A permutation, also called an âarrangement numberâ or âorderâ, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We hav
4 min read
Restore a permutation from the given helper array Given an array Q[] of size N - 1 such that each Q[i] = P[i + 1] - P[i] where P[] is the permutation of the first N natural numbers, the task is to find this permutation. If no valid permutation P[] can be found then print -1. Examples: Input: Q[] = {-2, 1} Output: 3 1 2 Input: Q[] = {1, 1, 1, 1} Out
7 min read
Distinct Numbers obtained by generating all permutations of a Binary String Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string. Examples: Input: S = "110"Output: {3, 5, 6}Explanation: All possible permutations are {"110", "101", "110", "101", "011", "011"}.Equivalent decimal num
8 min read