-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathNextPerm.java
59 lines (51 loc) · 1.3 KB
/
NextPerm.java
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
package Array;
import java.util.ArrayList;
import java.util.Collections;
/**
* Author - archit.s
* Date - 04/09/18
* Time - 12:28 PM
*/
public class NextPerm {
private void revSwap(ArrayList<Integer> a, int low, int high){
while(low<=high){
int temp = a.get(low);
a.set(low, a.get(high));
a.set(high, temp);
low++;
high--;
}
}
private int bSearch(ArrayList<Integer> a, int low, int high, int key){
int index = -1;
while(low<=high){
int mid = low + (high-low)/2;
if(a.get(mid) <= key){
high = mid -1;
}
else{
low = mid+1;
if(index == -1 || a.get(index)>=a.get(mid)){
index = mid;
}
}
}
return index;
}
public void nextPermutation(ArrayList<Integer> a) {
int i=a.size()-2;
while(i>=0 && a.get(i)>= a.get(i+1)){
i--;
}
if(i<0){
Collections.sort(a);
}
else{
int index = bSearch(a,i+1,a.size()-1,a.get(i));
int temp = a.get(i);
a.set(i, a.get(index));
a.set(index, temp);
revSwap(a, i+1, a.size()-1);
}
}
}