-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathNext_Permutation.java
63 lines (54 loc) · 1.54 KB
/
Next_Permutation.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
60
61
62
63
import java.util.Arrays;
public class nextPermutation {
public static int[] swap(int data[], int left, int right)
{
int temp = data[left];
data[left] = data[right];
data[right] = temp;
return data;
}
public static int[] reverse(int data[], int left, int right)
{
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
return data;
}
public static boolean findNextPermutation(int data[])
{
if (data.length <= 1)
return false;
int last = data.length - 2;
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
if (last < 0)
return false;
int nextGreater = data.length - 1;
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
data = swap(data, nextGreater, last);
data = reverse(data, last + 1, data.length - 1);
return true;
}
public static void main(String args[])
{
int data[] = { 1, 2, 3 };
if (!findNextPermutation(data))
System.out.println("There is no higher"
+ " order permutation "
+ "for the given data.");
else {
System.out.println(Arrays.toString(data));
}
}
}