简体   繁体   English

在这种情况下,递归到底如何工作?

[英]How EXACTLY does recursion work in this case?

I am new to this forum and I hope that I don't make any mistakes. 我是这个论坛的新手,希望我不会犯任何错误。 Here's my question. 这是我的问题。 I think I understand the basic principle of recursion and its implementation, yet I have problems to understand the EXACT steps the computer is doing when executing a recursive code. 我想我了解递归及其实现的基本原理,但是在理解递归代码执行时计算机正在执行的确切步骤时遇到了一些问题。

Here's an example: 这是一个例子:

public class Main { 公共班级主要{

public static void MyAlgorithm (int [] A, int l, int r ) {
    if (l<r) {
        int m = (l+r)/2;
        MyAlgorithm(A, l, m);

        for (int i = l; i<=r; i++) {
            System.out.println(A[i]);
        }

        MyAlgorithm(A, m+1, r);
    }


}
public static void main (String args[]) {

    int [] A = {1,2,3,4};

    MyAlgorithm (A, 0, 3);
}

} }

The output is: 12123434 输出为:12123434

But how does this exactly work? 但是,这到底如何工作? At first, the code calculates m as 2. It then performs the method again on the subarray (1,2) and puts this on a stack. 首先,代码将m计算为2。然后再次在子数组(1,2)上执行该方法,并将其放入堆栈中。 Then it does it again, takes the half and puts 1 on the stack. 然后再次执行,取一半并将1放入堆栈。 As far as I understand the issue, it then stops, pops 1 from the stack and prints it. 据我了解的问题,它然后停止,从堆栈中弹出1并进行打印。 But when does it put the 2 on the stack separately? 但是何时将2分别放在堆栈上? And when exactly does it start the recursion part with the other half? 以及何时准确地从另一半开始递归部分? I simply cannot really understand how the computer is executing the single steps and how it "knows" when to start calling the other half of the array recursively. 我根本无法真正理解计算机如何执行单个步骤以及如何“知道”何时开始递归调用数组的另一半。 I hope you understand my question and I am grateful for every response! 希望您能理解我的问题,感谢您的答复!

Thanks in advance :) 提前致谢 :)

Execution call will be something like this 执行调用将是这样的

MyAlgorithm(A,0,3) 
    (l < r : true)
     m = (0+3)/2=1
     MyAlgorithm(A,0,1) 
            (l < r : true) 
            m = (0+1)/2=0
            MyAlgorithm(A,0,0) 
                (l < r : false) return

            loop from l=0 to r=1
            System.out.println(A[0]);
            System.out.println(A[1]);

            //MyAlgorithm(A,m+1,r)
            MyAlgorithm(A,1,1) 
                (l < r : false) return

    loop from 1=0 to r=3
    System.out.println(A[0]);
    System.out.println(A[1]);
    System.out.println(A[3]);
    System.out.println(A[4]);

    //MyAlgorithm(A,m+1,r)
    MyAlgorithm(A,2,3)
        (l < r : true)
        m=(2+3)/2 = 2
        MyAlgorithm(A,2,2)
            (l < r : false) return

    loop from 1=2 to r=3
    System.out.println(A[2]);
    System.out.println(A[3]);

    MyAlgorithm(A,3,3)
            (l < r : false) return      
return

This leads to answer: 12123434 这导致答案:12123434

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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