I am trying to write a recursive function to produce all permutations of an array.
static int permus[] = new int[] { 1, 2, 3, 4, 5 };
static void testPermu(int start)
{
// Print it
System.out.println(Arrays.toString(permus));
int k;
for (int i = start + 1; i < permus.length; i++) {
// swap
k = permus[start];
permus[start] = permus[i];
permus[i] = k;
testPermu(i);
// unswap
k = permus[start];
permus[start] = permus[i];
permus[i] = k;
}
}
It's invoked as testPermu(0)
and should produce all permutations, however that does not work. How can I fix it?
It needs to be recursive, each time the function is invoked, it should get a fresh permutation.
output now is
[1, 2, 3, 4, 5] [2, 1, 3, 4, 5] [2, 3, 1, 4, 5] [2, 3, 4, 1, 5] [2, 3, 4, 5, 1] [2, 3, 5, 4, 1] [2, 4, 3, 1, 5] [2, 4, 3, 5, 1] [2, 5, 3, 4, 1] [3, 2, 1, 4, 5] [3, 2, 4, 1, 5] [3, 2, 4, 5, 1] [3, 2, 5, 4, 1] [4, 2, 3, 1, 5] [4, 2, 3, 5, 1] [5, 2, 3, 4, 1]
You can see that many of the permutations are missing.
I'm writing it in Java but I'll understand example in C, javascript or anything else as long as it's not using some library tricks not available in Java.
Three corrections are needed in order to work:
(start == permus.length-1)
, otherwise you'll see duplicatesfor
loop from i = start
, not i = start + 1
testPermu(start + 1);
instead of testPermu(i);
@Enric solution is nice, but using solution below we can avoid 80 swaps and perform only 24 swaps.
static void permutation(int[] a, int i, int j) {
for (; j < a.length && i < a.length; j++) {
int[] temp = null;
if (i != j) {
temp = swap(a, i, j);
System.out.println(Arrays.toString(temp));
}else{
temp = a;
}
permutation(temp, i + 1, i + 1);
}
}
public static void main(String[] args) {
int[] a = { 0, 1, 2, 3 };
permutation(a, 0, 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With