-
Notifications
You must be signed in to change notification settings - Fork 0
/
NextPermutation2.java
57 lines (50 loc) · 1.56 KB
/
NextPermutation2.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
import java.util.Arrays;
import java.util.Scanner;
public class NextPermutation2 {
public static void main(String[] args) {
System.out.println("Enter the number of elements in the array");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
nextPermutation(arr);
System.out.println(Arrays.toString(arr));
}
public static void nextPermutation(int[] nums) {
int index = -1;
int n = nums.length;
for (int i = n - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
index = i;
break;
}
System.out.println(index);
}
if (index == -1) {
reverseArray(nums, 0, n - 1);
// System.out.println(Arrays.toString(nums));
} else {
for (int i = n - 1; i >= index; i--) {
if (nums[i] > nums[index]) {
int temp = nums[i];
nums[i] = nums[index];
nums[index] = temp;
break;
}
}
reverseArray(nums, index + 1, n - 1);
}
}
public static void reverseArray(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}