递归:在程序中调用两次时递归是如何工作的?

时间:2016-09-10 18:26:44

标签: java recursion divide-and-conquer

该计划的输出是什么以及它将如何?

public class Recursion 
{
    static int p=100;
    public static void main(String args[])
    {
        divide(20);
    }
    public static void divide(int x)
    {
        System.out.println(x);
        if(x>1)
        {
            divide(x/2);
            divide(x/4);
        }
        //System.out.println(x);

    }
    public static void multiply(int x)
    {
        System.out.println("X="+x);
    }

}

请提供输出及其工作。

1 个答案:

答案 0 :(得分:0)

此修改可帮助您了解呼叫顺序。 (它只是为您的system.out.println())

添加了上下文
public class StackOverflowQuestions {

    public static void main(String args[]) {
        divide(20, "x=20, depth=0, initial call", 1);
    }

    public static void divide(int x, String callOrder, int depth) {
        System.out.println(callOrder);
        if (x > 1) {
            divide(x / 2, callOrder+" ; x="+x/2+",depth="+depth+",call=1", depth+1);
            divide(x / 4, callOrder+" ; x="+x/4+",depth="+depth+",call=2", depth+1);
        }
    }

}

这是输出:

x=20, depth=0, initial call
x=20, depth=0, initial call ; x=10,depth=1,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1 ; x=1,depth=4,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=2,depth=3,call=1 ; x=0,depth=4,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=5,depth=2,call=1 ; x=1,depth=3,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2 ; x=1,depth=3,call=1
x=20, depth=0, initial call ; x=10,depth=1,call=1 ; x=2,depth=2,call=2 ; x=0,depth=3,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1 ; x=1,depth=3,call=1
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=2,depth=2,call=1 ; x=0,depth=3,call=2
x=20, depth=0, initial call ; x=5,depth=1,call=2 ; x=1,depth=2,call=2

如您所见,在您遇到x< = 1的中断条件之前,始终会使用您的两个方法调用中的第一个。只有这样,程序才会到达第二行,并且再次发生相同的递归调用,直到满足中断条件为止。