CMPS 144   Computer Science 2
Sample Problems: Recursion

1. Consider the following recursive method:
   /* pre: n > 0
      post: ?
   */
   public static int goofy( int n )  {

      if (n == 1) 
         { return 0; }
      else if (n % 2 == 0)
         { return 1 + goofy( n/2 ); }
      else 
         { return goofy( n+1 ); }
   }

Note that the expression n % 2 == 0 is equivalent to the proposition "n is even".

Evaluate:

For a bonus, supply the method's missing post-condition. (Hint: the method implements a well-known mathematical function.)

Solution:

     goofy(5)                       goofy(15)
   = goofy(6)                     = goofy(16)
   = 1 + goofy(3)                 = 1 + goofy(8)
   = 1 + goofy(4)                 = 1 + 1 + goofy(4)
   = 1 + 1 + goofy(2)             = 1 + 1 + 1 + goofy(2)
   = 1 + 1 + 1 + goofy(1)         = 1 + 1 + 1 + 1 + goofy(1)
   = 1 + 1 + 1 + 0                = 1 + 1 + 1 + 1 + 0
   = 3                            = 4
Answer to bonus question: The value returned by goofy is ceiling(lg n), i.e., the smallest integer k such that 2k >= n.

2. We wish to develop a method that, given an array a[]of char and int's low and high, returns the minimum value occurring within a[low..high-1]. One approach is to do it recursively, using the fact that, in an array segment of length two or greater, the minimum element is the smaller among

  1. the first element in the segment and
  2. the minimum element in the remaining portion of the segment.
Fill in the following accordingly.
   /* pre:  0 <= low < high <= a.length
      post: value returned is minimum one occurring in a[low..high-1]
   */
   public static char minCharAry( char[] a, int low, int high )  {

      [ fill in, if necessary ]
      
      if  ( ? )  {       // base case (segment of length one)

         [ fill in ]

      }
      else  {            // recursive case (segment of length > 1)

         [ fill in ]

      }

   }
Solution:
   public static char minCharAry( char[] a, int low, int high )  {
      
      char result;

      if  ( low == high-1 )   // base case (segment of length one)

         { result = a[low]; }

      else  {            // recursive case (segment of length > 1)

         char minOfRest = minCharAry( a, low+1, high );

         // assertion: minOfRest = min value in a[low+1..high-1]

         if (a[low] <= minOfRest)
            { result = a[low]; }
         else
            { result = minOfRest; } 
      }
      return result;
   }