Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Generate all permutations of a string that follow given constraints
Next article icon

Heap’s Algorithm for generating permutations

Last Updated : 14 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:  

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>
 
 
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



Next Article
Generate all permutations of a string that follow given constraints

R

Rahul Agrawal
Improve
Article Tags :
  • DSA
  • Mathematical
Practice Tags :
  • Mathematical

Similar Reads

  • Generate all permutations of a string that follow given constraints
    Given a string, generate all permutations of it that do not contain 'B' after 'A', i.e., the string should not contain "AB" as a substring. Examples: Input : str = "ABC" Output : ACB, BAC, BCA, CBA Out of 6 permutations of "ABC", 4 follow the given constraint and 2 ("ABC" and "CAB") do not follow. I
    11 min read
  • Generate all permutation of a set in Python
    Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {
    2 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
  • Generate a N length Permutation having equal sized LIS from both ends
    Given an integer N, the task is to generate a permutation of elements in the range [1, N] in such order that the length of LIS from starting is equal to LIS from the end of the array. Print -1 if no such array exists. Examples: Input: N = 5Output: [1, 3, 5, 4, 2]Explanation:LIS from left side: [1, 3
    12 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
  • Generate all cyclic permutations of a number
    Given a number N, our task is to generate all the possible cyclic permutations of the number. A cyclic permutation shifts all the elements of a set by a fixed offset. For a set with elements [Tex]a_0 [/Tex], [Tex]a_1 [/Tex], ..., [Tex]a_n [/Tex], a cyclic permutation of one place to the left would y
    6 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
  • Count Permutations in a Sequence
    Given an array A consisting of N positive integers, find the total number of subsequences of the given array such that the chosen subsequence represents a permutation. Note: Sequence A is a subsequence of B if A can be obtained from B by deleting some(possibly, zero) elements without changing its or
    5 min read
  • BogoSort or Permutation Sort
    BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm one person can ever imagine. It is based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorte
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences