Lexicographically next permutation in C++


Here we will see how to generate lexicographically next permutation of a string in C++. The lexicographically next permutation is basically the greater permutation. For example, the next of “ACB” will be “BAC”. In some cases, the lexicographically next permutation is not present, like “BBB” or “DCBA” etc.

In C++ we can do it by using a library function called next_permutation(). This is present in the algorithm header file.

Example

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   string s = "DBAC";
   for(int i = 0; i<5; i++) {
      bool val = next_permutation(s.begin(), s.end());
      if (val == false) {
         cout << "No next permutation" << endl;
         break;
      } else
      cout << "Next: " << s << endl;
   }
}

Output

Next: DBCA
Next: DCAB
Next: DCBA
No next permutation

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements