-
Notifications
You must be signed in to change notification settings - Fork 0
/
Next_Permutation.cpp
81 lines (74 loc) · 1.69 KB
/
Next_Permutation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
void Reverse(int arr[], int start, int end)
{
while(start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
vector<int> nextPermutation(vector<int> &arr){
// code here
int n = arr.size();
int ind = -1;
for(int i = n - 2; i >= 0; i--)
{
if(arr[i] < arr[i+1])
{
ind = i;
break;
}
}
if(ind == -1)
{
Reverse(arr.data(), 0, (n - 1));
}
else
{
for(int i = n - 1; i > ind; i--)
{
if(arr[ind] < arr[i])
{
swap(arr[i], arr[ind]);
break;
}
}
Reverse(arr.data(), (ind+1), (n - 1));
}
return arr;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution ob;
int n = arr.size();
ob.nextPermutation(arr);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << "\n";
}
return 0;
}
// } Driver Code Ends