understanding basic recursion

后端 未结 8 2006
public static void main (String[] args)
{
    System.out.println(factorial(5));
}

public int factorial(int n)
{
    if(n <= 1){
        return 1;
    }
    else{         


        
相关标签:
8条回答
  • 2020-11-28 16:38

    Its important to note that "recursion" works differently in java (a procedural language) than it does in say Haskell or F# (functional languages).

    In Java when we invoke recursion we do so by evaluating the expression tree and resolving each part of it until we determine the value of each part of the expression. If we need to invoke another function we put in a place holder for all intermediate values at that point and then begin to build a new expression tree for the new function.

    In the case of recursion what we are doing is making a call to the same function, hopefully with different terminating values, which needs to be resolved before we can complete the evaluation of the current expression. These expansions are chained together repeatedly until one of two things happens 1) We reach a terminating expression which returns control to the caller (the first part of your if in this case), or we exhaust our ability to place intermediate values in storage and we return an exception (Stack overflow).

    In the first case we then begin resolving each of the expression trees from the top of the stack, working our way backwards until their are no stack entries left, at which point the expression tree resolves to the final value returned.

    Jim's answer is an excellent physical metaphor for this.

    0 讨论(0)
  • 2020-11-28 16:46

    Are you asking how recursion works internally? The one sentence answer is that every thread has a "call stack" and every time a method is called, a new entry gets pushed onto this stack, which has information about which method is called, and what the arguments were. When the method is finished it places its return value back on the same stack and the calling method pulls it off. So at its height your stack will look like

    factorial (1) called by factorial (2) called by factorial (3) called by factorial (4) called by factorial (5)

    The Wikipedia article on call stacks seems pretty thorough at first glance.

    0 讨论(0)
提交回复
热议问题