recursion in mergesort: two recursive calls

前端 未结 2 1903
小蘑菇
小蘑菇 2021-01-27 18:07
private void mergesort(int low, int high) {     //line 1
if (low < high) {                               //line 2
    int middle = (low + high)/2 ;               //li         


        
相关标签:
2条回答
  • 2021-01-27 18:32

    Regarding your second snippet :

    public static void recursionExample(int i){     
        if(i < 3){                                 
            recursionExample(i+1);  // this is called for the last time when i==2, i.e. the
                                    // last call is recursionExample(3). When that call 
                                    // returns, i is still equal 2, since calling  
                                    // recursionExample(i+1) doesn't change the value of the
                                    // local variable i of the current method call
    
            recursionExample(i-1);  // Therefore when this line is first called, i is equal 2
        }                                         
    } 
    
    0 讨论(0)
  • 2021-01-27 18:42

    Considering your second snippet, the order of calls is the following (represented as a tree for ease of understanding) :

    - recursionExample(0)
      - recursionExample(1)
        - recursionExample(2)
          - recursionExample(3), here no more recursion
          - recursionExample(1)
            ...
        - recursionExample(0)
          ...
      - recursionExample(-1)
        - recursionExample(0)
          ...
        - recursionExample(-2)
          ...
    
    0 讨论(0)
提交回复
热议问题