I have written an algorithm for solving string permutations algorithm. It's having a problem, somewhere it's printing wrong output. I have walked through my code multiple times for different inputs, but I am unable to find what mistake I have done.
Would someone explain where I have made a mistake?
public static void main(String args[]) throws Exception {
String str1 = "eat";
int len = str1.length();
char[] str = str1.toCharArray();
recurPerm(str,0,len);
}
static void recurPerm(char[] str, int strstartind, int sz) {
for(int i = strstartind; i < sz; i++){
if(i > strstartind) {
char temp = str[strstartind];
str[strstartind] = str[i];
str[i] = temp;
recurPerm(str, strstartind + 1, sz);
}
else {
recurPerm(str, strstartind + 1, sz);
}
}
if(strstartind >= sz){
System.out.println(str);
}
return;
}
Output
eat
eta
tea
tae
eat
eta
But correct output is
eat eta aet ate tae tea
I tried debugging too. I found it too hard to debug because recursion being involved.
aetandate.