-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation
More file actions
56 lines (53 loc) · 1.58 KB
/
Next Permutation
File metadata and controls
56 lines (53 loc) · 1.58 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
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
public class next_permutation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
nextper(arr); // Move the nextper call inside the while loop
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(); // Add a newline after printing each permutation
t--;
}
}
public static void nextper(int[] arr) {
int p = 0;
int q = 0;
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i + 1] > arr[i]) {
p = i;
break;
}
}
for (int j = arr.length - 1; j > p; j--) {
if (arr[j] > arr[p]) {
q = j;
break;
}
}
if (p == 0 && q == 0) {
reversing(arr, 0, arr.length - 1); // Adjust reversing function arguments
return;
}
int temp = arr[p];
arr[p] = arr[q];
arr[q] = temp;
reversing(arr, p + 1, arr.length - 1); // Adjust reversing function arguments
}
public static void reversing(int[] arr, int i, int j) {
while (i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
}