All Permutations Of An Array In C++

In this tutorial, we shall learn to compute all permutations of an array in C++. Here we shall be using STL’s next_permutation function. The std::next_permutation is used to rearrange the elements in the range [first, last) into the next lexicographically greater permutation.
A permutation is defined as each one of the possible arrangements that can be made in factorial N ways.

The permutation is ordered lexicographically to each other. Its syntax is:

bool next_permutation (BidirectionalIterator first,
                       BidirectionalIterator last);

Permutations Of An Array

The display function takes two arguments first one is an array and the next is its size. Similarly, the Find_Permtations function takes an array and next is its size. We have also used the std::sort which will sort the array from index a to index a+n that is from index 0 to the last index of the array. Sorting is done to get the numbers in lexicographical order starting from the first number.

#include <bits/stdc++.h>
typedef long long ll; // Macro for long long
using namespace std;
void display(ll* , ll) ; // Function for displaying the array 
void Find_Permutations(ll* , ll ) ; // Function to find the permutations of array 

int main() 
{ 
  
    ll a[] = { 1, 2, 3, 4 };
  
    ll n = sizeof(a) / sizeof(a[0]); 
  
    Find_Permutations(a, n); 
  
    return 0; 
} 
void display(ll a[], ll n) 
{ 
    for (ll i = 0; i < n; i++) { 
        cout << a[i] << "  "; 
    } 
    cout << endl; 
} void Find_Permutations(ll a[], ll n) 
{ 
  
    // Sort the given array 
    sort(a, a + n); 
  
    // Find all possible permutations 
    cout << "Possible permutations are:\n"; 
    do { 
        display(a, n); 
    } while (next_permutation(a, a + n)); 
}

It will produce the output:

Possible permutations are:
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

You may also like to learn:

Leave a Reply

Your email address will not be published. Required fields are marked *