Monday, May 16, 2016

Tracing a recursive function .


Observations :



Problem :  Find the values of n printed to console .


public static void function123(int n){
  
   if(n<=0){
    
    return;
   }
  
   System.out.println(n);
   
   function123(n-2);
   function123(n-3);
 
   
   System.out.println(n);
  
 }

Solution :


Problem :  Find the values of n printed to console .

static int fib( int n )
 {
    if ( n == 0 )  // base case 1
      return 1;
    else if ( n == 1 )  // base case 2
      return 2;
    else
      {
         int resultA = fib( n - 1 ); // "A"
         int resultB = fib( n - 2 ); // "B"
         
         System.out.println(resultA+resultB);
         
         return resultA + resultB;
      }
 }

Solution :



Problem :  Trace the path of recursion

public int searchWithR(int[] arr, int value, int lo, int hi) {

  // exit condition
  if (lo > hi) {

   // return special value if term is not found;

   return -1;
  }

  int mid = (lo + hi) / 2;

  if (arr[mid] == value) {

   return mid;

  } else if (value < arr[mid]) {

   // change value of high , one position left of mid
   return searchWithR(arr, value, lo, mid - 1);

  } else {

   // change value of low , one position right of mid
   return searchWithR(arr, value, mid + 1, hi);
  }

 }

No comments: