After reading so many post of "generating permutation of string", I tried to write it in Java. 1) Take the first character start swapping with rest of the character in the combination.
But when I tried to implement it using recursion it gave me only two string for a string of length 3 :(.
public static void main(String[] args) {
char a[]= "123".toCharArray();
printPermutation(a,0);
}
private static void printPermutation(char[] a, int i) {
if(i==a.length-1)
System.out.println(new String(a));
else{
for(int x=i+1;x<a.length;x++)
{
swap(a,i,x);
printPermutation(a,x );
swap(a,i,x);
}
}
}
private static void swap(char[] a, int i, int x) {
char t=a[i];
a[i]=a[x];
a[x]=t;
}
I am expecting 6 string to be printed.
expected: 123, 132, 213, 231, 312, 321