简体   繁体   中英

Problem in Understanding Recursion - Java

I got the code from this question, I ran it in Eclipse and the code was fine, but I confused myself in how the recursion order goes internally.

public class Permute {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter a string");
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(
                System.in));
        String text = bufReader.readLine();
        shuffle("", text);
    }

    public static void shuffle(String dummy, String input) {
        if (input.length() <= 1)
            System.out.println(dummy + input);
        else {
            for (int i = 0; i < input.length(); i++) {
                input = input.substring(i, i + 1) + input.substring(0, i)
                        + input.substring(i + 1);
                shuffle(dummy + input.substring(0, 1), input.substring(1));

            }
        }
    }
}

I found difficulty in understanding recursion in the for loop of Shuffle . Any pointers in decoding the recursion steps?

EDIT : Okay this is my understanding, say suppose my input is ABC and when i run in the first loop , i get dummy = A and input = BC, so the immediate step would be to go down the recursion for input = BC and dummy = A and then come back to iterate i for the initial input ?

Think of it as dividing the job in steps. Your shuffle function takes two arguments, dummy for the part of the string that is already shuffled, and input for the part of the string that still has to be shuffled.

At every step, you shuffle the first character of input :

        for (int i = 0; i < input.length(); i++) {
            input = input.substring(i, i + 1) + input.substring(0, i)
                    + input.substring(i + 1);

and then, recursively apply the algorhythm, with the part already shuffled being a character longer:

            shuffle(dummy + input.substring(0, 1), input.substring(1));

Until there is nothing more to shuffle:

    if (input.length() <= 1)
        System.out.println(dummy + input);

It exhaustively shuffles the input by the inputs length, recursively. So once each recursion has shuffled the string by the i'th term, it returns.

This would be an n-squared complexity algorithm in big-O notation.

The shuffling is tricky to work out without a debugger ;)

Add a global counter:

static int depth = 0; /* calling depth of the recursive method */

Add as the first line of shuffle :

System.out.printf("%" + depth++ + "s call dummy='%s' input='%s'\n", "", dummy, input);

Add as the last line of shuffle :

System.out.printf("%" + --depth + "s return\n", "");

Run the program. Now you can see what happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM