fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. void nextPermutation(vector<int> &arr) {
  7.  
  8. int n = arr.size();
  9.  
  10. // Find the pivot index
  11. int pivot = -1;
  12. for (int i = n - 2; i >= 0; i--) {
  13. if (arr[i] < arr[i + 1]) {
  14. pivot = i;
  15. break;
  16. }
  17. }
  18.  
  19. // If pivot point does not exist, reverse the
  20. // whole array
  21. if (pivot == -1) {
  22. reverse(arr.begin(), arr.end());
  23. return;
  24. }
  25.  
  26. // find the element from the right that
  27. // is greater than pivot
  28. for (int i = n - 1; i > pivot; i--) {
  29. if (arr[i] > arr[pivot]) {
  30. swap(arr[i], arr[pivot]);
  31. break;
  32. }
  33. }
  34.  
  35. // Reverse the elements from pivot + 1 to the
  36. // end to get the next permutation
  37. reverse(arr.begin() + pivot + 1, arr.end());
  38. }
  39.  
  40. int main() {
  41.  
  42. vector<int> arr = {0, 1, 2, 5, 7, 4 };
  43. nextPermutation(arr);
  44. for (int x : arr)
  45. cout << x << " ";
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
0 1 2 7 4 5