-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.java
More file actions
32 lines (32 loc) · 839 Bytes
/
permutations.java
File metadata and controls
32 lines (32 loc) · 839 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
public class permutations {
public static void generate(int[] arr, int k){
if(k ==1)
check(arr);
else{
generate(arr, k-1);
for(int i=0;i<k-1;i++){
if(k%2 == 0){
swap(arr,i,k-1);
} else {
swap( arr,0,k-1);
}
generate(arr,k-1);
}
}
}
public static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void check(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {1, 2, 3};
generate(arr, arr.length);
}
}