I recently learn the algorithm,today I am strained with a problem:why the swap function run twice in the string permutation recursive way? How can I understand it?Could you help me?
public class Permutation {
public static void swap(char[] str, int i, int j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
public static void permutation(char[] str) {
if (str==null)return;
permutation(str,0);
}
private static void permutation(char[] str, int begin) {
if (begin == str.length) {
System.out.println(Arrays.toString(str));
} else {
for (int i = begin;i<str.length;i++) {
swap(str, begin, i);
permutation(str, begin + 1);
swap(str, begin, i);
}
}
}
public static void main(String[] args) {
char[] a = {'a', 'b', 'c', 'd'};
permutation(a);
}
}