简体   繁体   中英

Why does the recursion goes to else block instead of if?

class myclass {
   static int fun(int a[],int n){
      int x;

      if(n == 1){
        return a[0];
      }
      else{
           x = fun(a, n-1);

          if(x > a[n-1])
              return x;
          else
             return a[n-1];
      }
}
 public static void main(String[] args){
     int arr[] = {12, 10, 30, 50, 100};
     System.out.println(fun(arr, 5));}
}

Why is the output 100 and not 12. I am not getting why the last recursive call when the value of n is 1, it is going to else block instead of if.

This is because you're looking for maximum in the array. Changing if(x > a[n-1]) to if(x < a[n-1]) will make your program return 10 for given input.

It is because you return at the end to the prior instance of the same function, thus your method calls and returns look like this (each level indentation is a function call and its return). If you know how to use a debugger, step though your code and see and draw this diagram as you go, this will help you be able to mentally visualize the recursive calls and the values returned each time.

fun(a[],5) 
 |   fun(a[],4) 
 |   |   fun(a[],3)
 |   |   |  fun(a[],2)
 |   |   |   |  fun(a[],1)
 |   |   |   |  return 12
 |   |   |   return 12
 |   |   return 30
 |   return 50
 return 100
  1. N=1, x= 12, 12 > a[0] (12) ---> return a[1-1] = 12
  2. N=2. x=12, 12 > a[1] (10) --> return x = 12;
  3. N=3. x=12, 12> a[2] (30) --> return a[3-1] = 30
  4. N =4 x =30, 30 > a[3] (50) --> return a[4-1] = 50
  5. N=5 x =50, 50 > a[4] (50) ---> return a[5-1] = 100

Here in details why the result is 100 .

public class myclass {
 static int fun(int a[],int n)
{
 int x;
 if(n == 1)
{
 return a[0];   // Step (2) --> return x = 12, now again n = 5 then continue on line        
}
 else
{
 x = fun(a, n-1); // Step (1) --> this line is same as x = fun(a, 1)
 if(x > a[n-1])     // Step (3) --> at this point n = 5 again and x = 12 while a[4] = 100 which is not less than x, statement 12 > 100 is false, move on to else block
 return x;
 else
 return a[n-1];  // Step (4) --> return a[4] which is 100 as see above
}
}
 public static void main(String[] args)
{
 int arr[] = {12, 10, 30, 50, 100};
 System.out.println(fun(arr, arr.length));}
}

Hopefully, you will understand what you have been missing on your recursion example!

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