-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
38 lines (33 loc) · 865 Bytes
/
Permutations.java
File metadata and controls
38 lines (33 loc) · 865 Bytes
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
package devjava;
public class Permutations {
public static <T> void printAllRecursive(int n, T[] elements, char delimiter) {
if (n == 1) {
printArray(elements);
} else {
for (int i = 0; i < n - 1; i++) {
printAllRecursive(n - 1, elements, delimiter);
if (n % 2 == 0) {
swap(elements, i, n - 1);
} else {
swap(elements, 0, n - 1);
}
}
printAllRecursive(n - 1, elements, delimiter);
}
}
private static <T> void swap(T[] input, int a, int b) {
T tmp = input[a];
input[a] = input[b];
input[b] = tmp;
}
private static <T> void printArray(T[] input) {
System.out.print('\n');
for (int i = 0; i < input.length; i++) {
System.out.print(input[i]);
}
}
public static void main(String[] args) {
Character[] temp = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
printAllRecursive(9, temp, ',');
}
}