I noted down this code, to find the permutations of the entered String, in class today.
However, I don't seem to understand what's going on in the for loop in the , doPermute function especially after the part where it calls itself. How does it manage to execute the code written after it calls itself?! Would greatly appreciate some explanation.
P.S I know that this question might seem a bit amateur, I apologize for that as I haven't fully understood recursive functions as of yet.
Code :
import java.util.Scanner;
public class Permutation {
public static void main (String args[])
{
System.out.println(" Enter the string to show permutations ");
Scanner in = new Scanner(System.in);
String original=in.nextLine();
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Results are :");
System.out.println("");
System.out.println("");
permute(original);
}
public static void permute( String input)
{
int inputLength = input.length();
boolean used [] = new boolean[ inputLength ];
StringBuffer outputString = new StringBuffer();
char in[] = input.toCharArray( );
doPermute ( in, outputString, used, inputLength, 0 );
}
public static void doPermute ( char in[], StringBuffer outputString,
boolean used[], int inputLength, int level)
{
if( level == inputLength) {
System.out.println ( outputString.toString());
return;
}
for( int i = 0; i < inputLength; i++ )
{
if( used[i] ) continue;
outputString.append( in[i] );
used[i] = true;
doPermute( in, outputString, used, inputLength, level + 1 );
used[i] = false;
outputString.setLength( outputString.length() - 1 );
}
}
}