Find All Permutations of an Array using STL in C++
The permutation of an array refers to a rearrangement of its elements in every possible order. In this article, we will learn how to generate all possible permutation of an array using STL in C++.
The simplest method to find all the permutations of an array is to use next_permutation(). The array has to be sorted in ascending order because this function generate the next lexicographically larger permutation of an array. The below example shows how to implement this method:
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
// Generate all permuatation of an array
do {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
} while (next_permutation(arr, arr + n));
return 0;
}
Output
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
Explanation: The next_permutation() method returns true if the next permutation exists and rearranges the arr to it and returns false if it doesn't exits. So, we used a loop in the above program that runs till next_permutation() returns false.
Note: This function modifies the given array to generate its next permutation.
Using prev_permutation() Function
The prev_permutation() does just the opposite of the prev_permutation() function and generate all the previous permutation of the given array. But the given array should be sorted in the descending order.
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, greater<int>());
// Generate all permuatation of an array
do {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
} while (prev_permutation(arr, arr + n));
return 0;
}
Output
3 2 1 3 1 2 2 3 1 2 1 3 1 3 2 1 2 3