std::next_permutation and std::prev_permutation in C++

Let’s learn about std::next_permutation and  std::prev_permutation in C++. Let’s first know about permutations:
We know that a permutation is the n! possible arrangements of the elements, where n is the number of elements. The permutations are ordered differently after comparing them lexicographically to each other.

The first lexicographically sorted permutation will have all its elements in ascending order, this would be lexicographically smaller to all other permutations, and the largest has all its elements sorted in descending order.
Let’s understand the codes for std::next_permutation and std::prev_permutation:

std::next_permutation

We use std::next_permutation to rearrange the elements of a permutation to the next lexicographical greater permutation.

Syntax:
next_permutation( first iterator, last iterator)

Where the first and the last iterator are the positions of the starting and ending of the sequence for which we need the next permutation.
It returns TRUE if it can rearrange the sequence.
Code:

#include <iostream>
#include <algorithm>  

using namespace std; 
  
int main() 
{ 
    int arr[] = { 1, 2, 3 }; 
  
  
    cout << "The next lexicographical permutation:\n"; 
    
    next_permutation(arr, arr + 3);                    
  
    for(int i=0;i<3;i++)
        cout<<arr[i];
    return 0; 
}
Output: 
The next lexicographical permutation:
1 3 2

std::prev_permutation

We use std::prev_permutation to rearrange the elements of a permutation to the previous lexicographical smaller permutation.

Syntax:
prev_permutation( first iterator, last iterator)

Where the first and the last iterator are the positions of the starting and ending of the sequence for which we need the previous permutation.
It returns TRUE if it can rearrange the sequence.
Code:

#include <iostream>
#include <algorithm>  

using namespace std; 
  
int main() 
{ 
    int arr[] = { 3, 2, 1 }; 
  
  
    cout << "The previous lexicographical permutation:\n"; 
    
    prev_permutation(arr, arr + 3); 
  
    for(int i=0;i<3;i++)
        cout<<arr[i];
    return 0; 
}
Output: 
The previous lexicographical permutation:
3 1 2

Leave a Reply

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