forked from pratyushmp/code_opensource_2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
36 lines (28 loc) · 843 Bytes
/
NextPermutation.java
File metadata and controls
36 lines (28 loc) · 843 Bytes
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
public class Solution {
public void nextPermutation(ArrayList<Integer> a) {
boolean swapped = false;
int index = -1;
for(int i = a.size() - 1; i>0; i--) {
if(a.get(i) > a.get(i-1)) {
index = i-1;
swapped = true;
break;
}
}
if(!swapped) {
Collections.reverse(a);
return;
}
int swapIndex = -1;
for(int j = a.size() - 1; j>index; j--) {
if(a.get(j) > a.get(index)) {
swapIndex = j;
break;
}
}
int ele = a.get(index);
a.set(index, a.get(swapIndex));
a.set(swapIndex, ele);
Collections.sort(a.subList(index+1, a.size()));
}
}