forked from black-shadows/InterviewBit-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.cpp
More file actions
50 lines (41 loc) · 1.15 KB
/
Copy pathNextPermutation.cpp
File metadata and controls
50 lines (41 loc) · 1.15 KB
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
// https://www.interviewbit.com/problems/next-permutation/
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void swapWith(int num, vector<int>& A, int i){
int min = A[i];
int j = i, index = i;
for(j = i; j < A.size(); j++){
if(min > A[j] && A[j] > A[num]){
index = j;
min = A[j];
}
}
swap(A[index], A[num]);
}
bool myFun(int i, int j){
return i > j;
}
void Solution::nextPermutation(vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
if(A.size() == 0 || A.size() == 1){
return;
}
int flag = 0;
for(int i = A.size()-1; i > 0; i--){
if(A[i] > A[i-1]){
swapWith(i-1, A, i);
sort(A.begin()+i, A.end());
flag = 1;
break;
}
}
if(flag == 0){
sort(A.begin(), A.end());
}
}