Advertisement
jasonpogi1669

Next Permutation Implementation using C++

May 24th, 2022
756
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. bool NextPermutation(int arr[], int sz) {
  6.     int n = sz;
  7.     int i = n - 2;
  8.     while (i >= 0 && arr[i] >= arr[i + 1]) {
  9.         i--;
  10.     }
  11.     if (i == -1) {
  12.         return false;
  13.     }
  14.     int j = i + 1;
  15.     while (j < n && arr[j] > arr[i]) {
  16.         j++;
  17.     }
  18.     j--;
  19.     swap(arr[i], arr[j]);
  20.     int left = i + 1;
  21.     int right = n - 1;
  22.     while (left < right) {
  23.         swap(arr[left], arr[right]);
  24.         left++;
  25.         right--;
  26.     }
  27.     return true;
  28. }
  29.  
  30. int main() {
  31.     int arr[] = {1, 2, 3};
  32.     while (true) {
  33.         for (int i = 0; i < 3; i++) {
  34.             cout << arr[i] << " ";
  35.         }
  36.         cout << '\n';
  37.         if (!NextPermutation(arr, 3)) {
  38.             break;
  39.         }
  40.     }
  41.     return 0;  
  42. }
  43.  
Advertisement
RAW Paste Data Copied
Advertisement