-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
46 lines (38 loc) · 1.05 KB
/
NextPermutation.java
File metadata and controls
46 lines (38 loc) · 1.05 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
package Array;
public class NextPermutation {
public static void nextPermutation(int[] arr) {
int n = arr.length, i, j;
for (i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
break;
}
}
if (i < 0) {
reverse(arr, 0, arr.length - 1);
} else {
// Find the rightmost successor to the pivot element.
for (j = n - 1; j > i; j--) {
if (arr[j] > arr[i]) {
break;
}
}
// Swap the pivot and the successor.
swap(arr, i, j);
reverse(arr, i + 1, arr.length - 1);
}
}
public static void reverse(int[] arr, int start, int end) {
while (start < end) {
swap(arr, start, end);
start++;
end--;
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
}
}