SlideShare a Scribd company logo
1 of 52
Chapter 20 Recursion




Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                     rights reserved.
                                                                                               1
Motivations
Suppose you want to find all the files under a
directory that contains a particular word. How do
you solve this problem? There are several ways to
solve this problem. An intuitive solution is to use
recursion by searching the files in the
subdirectories recursively.




         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        2
Motivations
H-trees, depicted in Figure 20.1, are used in a very large-
scale integration (VLSI) design as a clock distribution
network for routing timing signals to all parts of a chip
with equal propagation delays. How do you write a
program to display H-trees? A good approach is to use
recursion.




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          3
Objectives
   To describe what a recursive method is and the benefits of using recursion
    (§20.1).
   To develop recursive methods for recursive mathematical functions (§§20.2–
    20.3).
   To explain how recursive method calls are handled in a call stack (§§20.2–20.3).
   To solve problems using recursion (§20.4).
   To use an overloaded helper method to derive a recursive method (§20.5).
   To implement a selection sort using recursion (§20.5.1).
   To implement a binary search using recursion (§20.5.2).
   To get the directory size using recursion (§20.6).
   To solve the Towers of Hanoi problem using recursion (§20.7).
   To draw fractals using recursion (§20.8).
   To discover the relationship and difference between recursion and iteration
    (§20.9).
   To know tail-recursive methods and why they are desirable (§20.10).
                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                               4
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);

n! = n * (n-1)!




      ComputeFactorial                                                                Run
         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        5
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);

 factorial(3)




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           6
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);

 factorial(3) = 3 * factorial(2)




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           7
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);

 factorial(3) = 3 * factorial(2)
              = 3 * (2 * factorial(1))




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           8
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);

 factorial(3) = 3 * factorial(2)
              = 3 * (2 * factorial(1))
              = 3 * ( 2 * (1 * factorial(0)))




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           9
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);
 factorial(3) = 3 * factorial(2)
              = 3 * (2 * factorial(1))
              = 3 * ( 2 * (1 * factorial(0)))
              = 3 * ( 2 * ( 1 * 1)))




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           10
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);

 factorial(3) = 3 * factorial(2)
              = 3 * (2 * factorial(1))
              = 3 * ( 2 * (1 * factorial(0)))
              = 3 * ( 2 * ( 1 * 1)))
              = 3 * ( 2 * 1)



            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           11
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);

 factorial(3) = 3 * factorial(2)
              = 3 * (2 * factorial(1))
              = 3 * ( 2 * (1 * factorial(0)))
              = 3 * ( 2 * ( 1 * 1)))
              = 3 * ( 2 * 1)
              =3*2


            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           12
animation

                  Computing Factorial
                                                                                 factorial(0) = 1;
                                                                                 factorial(n) = n*factorial(n-1);
 factorial(4) = 4 * factorial(3)
              = 4 * 3 * factorial(2)
              = 4 * 3 * (2 * factorial(1))
              = 4 * 3 * ( 2 * (1 * factorial(0)))
              = 4 * 3 * ( 2 * ( 1 * 1)))
              = 4 * 3 * ( 2 * 1)
              =4*3*2
              =4*6
              = 24
            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           13
animation

                          Trace Recursive factorial
                                                                                                  Executes factorial(4)


                                  factorial(4)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2
                                                                                                                          Stack
                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1
                                              return 1 * factorial(0)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1
                                                          return 1                                                      Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                             14
animation

                          Trace Recursive factorial

                                  factorial(4)
                                           Step 0: executes factorial(4)
Step 9: return 24                                                                                      Executes factorial(3)
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1
                                              return 1 * factorial(0)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   15
animation

                          Trace Recursive factorial

                                  factorial(4)                                                       Executes factorial(2)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1
                                              return 1 * factorial(0)                                                   Space Required
                                                                                                                         for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   16
animation

                          Trace Recursive factorial

                                  factorial(4)                                                       Executes factorial(1)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1                                                                                    Space Required
                                                                                                                         for factorial(2)
                                              return 1 * factorial(0)                                                   Space Required
                                                                                                                         for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   17
animation

                          Trace Recursive factorial

                                  factorial(4)                                                       Executes factorial(0)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                                                                        Space Required
                                                                 Step 3: executes factorial(1)                           for factorial(1)
                    Step 6: return 1                                                                                    Space Required
                                                                                                                         for factorial(2)
                                              return 1 * factorial(0)                                                   Space Required
                                                                                                                         for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   18
animation

                          Trace Recursive factorial

                                  factorial(4)                                                                 returns 1
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                     Stack

                                                                                                                           Space Required
                                           return 2 * factorial(1)                                                          for factorial(0)
                                                                                                                           Space Required
                                                                 Step 3: executes factorial(1)                              for factorial(1)
                    Step 6: return 1                                                                                       Space Required
                                                                                                                            for factorial(2)
                                              return 1 * factorial(0)                                                      Space Required
                                                                                                                            for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                          Space Required
                                                                                                                            for factorial(4)

                                                          return 1                                                          Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                      19
animation

                          Trace Recursive factorial

                                  factorial(4)                                                         returns factorial(0)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                                                                        Space Required
                                                                 Step 3: executes factorial(1)                           for factorial(1)
                    Step 6: return 1                                                                                    Space Required
                                                                                                                         for factorial(2)
                                              return 1 * factorial(0)                                                   Space Required
                                                                                                                         for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   20
animation

                          Trace Recursive factorial

                                  factorial(4)                                                         returns factorial(1)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1                                                                                    Space Required
                                                                                                                         for factorial(2)
                                              return 1 * factorial(0)                                                   Space Required
                                                                                                                         for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   21
animation

                          Trace Recursive factorial

                                  factorial(4)                                                         returns factorial(2)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1
                                              return 1 * factorial(0)                                                   Space Required
                                                                                                                         for factorial(3)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   22
animation

                          Trace Recursive factorial

                                  factorial(4)                                                         returns factorial(3)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                                  Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1
                                              return 1 * factorial(0)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1                                                                       Space Required
                                                                                                                         for factorial(4)

                                                          return 1                                                       Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                   23
animation

                          Trace Recursive factorial
                                                                                    returns factorial(4)


                                  factorial(4)
                                           Step 0: executes factorial(4)
Step 9: return 24
                            return 4 * factorial(3)
                                                 Step 1: executes factorial(3)
      Step 8: return 6
                                  return 3 * factorial(2)
                                                         Step 2: executes factorial(2)
            Step 7: return 2                                                                                               Stack


                                           return 2 * factorial(1)
                                                                 Step 3: executes factorial(1)
                    Step 6: return 1
                                              return 1 * factorial(0)
                                                                Step 4: executes factorial(0)
                                 Step 5: return 1
                                                          return 1                                                      Main method




                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                                24
factorial(4) Stack Trace
                                                                                                               5 Space Required
                                                                                                                  for factorial(0)

                                                                                   4 Space Required
                                                                                      for factorial(1)
                                                                                                                 Space Required
                                                                                                                  for factorial(1)

                                                         3 Space Required
                                                            for factorial(2)
                                                                                     Space Required
                                                                                      for factorial(2)
                                                                                                                 Space Required
                                                                                                                  for factorial(2)

                             2 Space Required
                                for factorial(3)
                                                           Space Required
                                                            for factorial(3)
                                                                                     Space Required
                                                                                      for factorial(3)
                                                                                                                 Space Required
                                                                                                                  for factorial(3)

1 Space Required
   for factorial(4)
                               Space Required
                                for factorial(4)
                                                           Space Required
                                                            for factorial(4)
                                                                                     Space Required
                                                                                      for factorial(4)
                                                                                                                 Space Required
                                                                                                                  for factorial(4)




6 Space Required
   for factorial(1)
  Space Required             7 Space Required
   for factorial(2)             for factorial(2)
  Space Required               Space Required            8 Space Required
   for factorial(3)             for factorial(3)            for factorial(3)
  Space Required               Space Required              Space Required          9 Space Required
   for factorial(4)             for factorial(4)            for factorial(4)          for factorial(4)




                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                                                     25
Other Examples
f(0) = 0;
f(n) = n + f(n-1);




        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       26
Fibonacci Numbers
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89…
              indices: 0 1 2 3 4 5 6 7                                            8       9        10 11

fib(0) = 0;
fib(1) = 1;
fib(index) = fib(index -1) + fib(index -2); index >=2


fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0)
+fib(1) = 1 + fib(1) = 1 + 1 = 2


              ComputeFibonacci                                                                      Run
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             27
Fibonnaci Numbers, cont.
                                                                                                                             fib(4)
                                                                                      17: return fib(4)                               0: call fib(4)

                                                                                                                 return fib(3) + fib(2)
                                                                                                                                                                     11: call fib(2)
                                                                   10: return fib(3)

                                                                                                            1: call fib(3)                    16: return fib(2)

                                                            return fib(2) + fib(1)                                                                                return fib(1) + fib(0)
                     7: return fib(2)                                                           8: call fib(1)                                                                             14: return fib(0)
                                                              2: call fib(2)                                                 13: return fib(1)                    12: call fib(1)


                                                                             9: return fib(1)                                                                        15: return fib(0)
                        return fib(1) + fib(0)                                                        return 1                          return 1                                             return 0
4: return fib(1)                                            5: call fib(0)

                        3: call fib(1)

          return 1                       6: return fib(0)           return 0




                                    Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                                         rights reserved.
                                                                                                                                                                                            28
Characteristics of Recursion
All recursive methods have the following characteristics:

   – One or more base cases (the simplest case) are used to stop
     recursion.
   – Every recursive call reduces the original problem, bringing it
     increasingly closer to a base case until it becomes that case.

In general, to solve a problem using recursion, you break it
into subproblems. If a subproblem resembles the original
problem, you can apply the same approach to solve the
subproblem recursively. This subproblem is almost the
same as the original problem in nature with a smaller size.
            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           29
Problem Solving Using Recursion
Let us consider a simple problem of printing a message for
n times. You can break the problem into two subproblems:
one is to print the message one time and the other is to print
the message for n-1 times. The second problem is the same
as the original problem with a smaller size. The base case
for the problem is n==0. You can solve this problem using
recursion as follows:
        public static void nPrintln(String message, int times) {
          if (times >= 1) {
            System.out.println(message);
            nPrintln(message, times - 1);
          } // The base case is times == 0
        }
           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          30
Think Recursively
Many of the problems presented in the early chapters can
be solved using recursion if you think recursively. For
example, the palindrome problem in Listing 7.1 can be
solved recursively as follows:
 public static boolean isPalindrome(String s) {
   if (s.length() <= 1) // Base case
     return true;
   else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case
     return false;
   else
     return isPalindrome(s.substring(1, s.length() - 1));
 }
             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                            31
Recursive Helper Methods
The preceding recursive isPalindrome method is not
efficient, because it creates a new string for every recursive
call. To avoid creating new strings, use a helper method:
 public static boolean isPalindrome(String s) {
   return isPalindrome(s, 0, s.length() - 1);
 }
 public static boolean isPalindrome(String s, int low, int high) {
   if (high <= low) // Base case
     return true;
   else if (s.charAt(low) != s.charAt(high)) // Base case
     return false;
   else
     return isPalindrome(s, low + 1, high - 1);
 }
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             32
Recursive Selection Sort
1.   Find the smallest number in the list and swaps it
     with the first number.
2.   Ignore the first number and sort the remaining
     smaller list recursively.



     RecursiveSelectionSort




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          33
Recursive Binary Search
1.   Case 1: If the key is less than the middle element,
     recursively search the key in the first half of the array.
2.   Case 2: If the key is equal to the middle element, the
     search ends with a match.
3.   Case 3: If the key is greater than the middle element,
     recursively search the key in the second half of the
     array.

     RecursiveBinarySearch



            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           34
Recursive Implementation
/** Use binary search to find the key in the list */
public static int recursiveBinarySearch(int[] list, int key) {
  int low = 0;
  int high = list.length - 1;
  return recursiveBinarySearch(list, key, low, high);
}

/** Use binary search to find the key in the list between
    list[low] list[high] */
public static int recursiveBinarySearch(int[] list, int key,
  int low, int high) {
  if (low > high) // The list has been exhausted without a match
    return -low - 1;

    int mid = (low + high) / 2;
    if (key < list[mid])
      return recursiveBinarySearch(list, key, low, mid - 1);
    else if (key == list[mid])
      return mid;
    else
      return recursiveBinarySearch(list, key, mid + 1, high);
}
              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             35
Directory Size
The preceding examples can easily be solved without using
  recursion. This section presents a problem that is
  difficult to solve without using recursion. The problem is
  to find the size of a directory. The size of a directory is
  the sum of the sizes of all files in the directory. A
  directory may contain subdirectories. Suppose a
  directory contains files , , ..., , and subdirectories , , ..., ,
  as shown below.
                                                       directory




       f1   f2       ...        fm                    d1                         d2               ...           dn
      1     1                  1                      1                         1                               1


                 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                      rights reserved.
                                                                                                                     36
Directory Size
The size of the directory can be defined recursively as
  follows:
size( d )   size( f1 )      size( f 2 ) ...             size( f m )         size(d1 )           size(d 2 ) ...   size( d n )




              DirectorySize                                                                  Run




                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                                    37
Towers of Hanoi
 There  are n disks labeled 1, 2, 3, . . ., n, and three
  towers labeled A, B, and C.
 No disk can be on top of a smaller disk at any
  time.
 All the disks are initially placed on tower A.
 Only one disk can be moved at a time, and it must
  be the top disk on the tower.


          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         38
Towers of Hanoi, cont.
                 A                     B                  C
                                                                         A                     B                  C

                               Original position                                Step 4: Move disk 3 from A to B




                 A                     B                  C
                                                                         A                     B                  C

                        Step 1: Move disk 1 from A to B                         Step 5: Move disk 1 from C to A




                 A                     B                  C
                                                                         A                     B                  C

                        Step 2: Move disk 2 from A to C                         Step 6: Move disk 2 from C to B




                 A                     B                  C
                                                                         A                     B                  C

                        Step 3: Move disk 1 from B to C                         Step 7: Mve disk 1 from A to B




       Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                            rights reserved.
                                                                                                                      39
Solution to Towers of Hanoi
The Towers of Hanoi problem can be decomposed into three
subproblems.

               n-1 disks                                                                                                              n-1 disks




           .
           .                                                                                                                      .
           .                                                                                                                      .
                                                                                                                                  .



                                                                              A                           B                           C
           A                          B                        C

                             Original position                                          Step2: Move disk n from A to C



                                                                  n-1 disks                               n-1 disks




                                                              .                                       .
                                                              .                                       .
                                                              .                                       .




           A                          B                           C           A                           B                           C

           Step 1: Move the first n-1 disks from A to C recursively               Step3: Move n-1 disks from C to B recursively



                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                                                                  40
Solution to Towers of Hanoi

   Move the first n - 1 disks from A to C with the assistance of tower
    B.
   Move disk n from A to B.
   Move n - 1 disks from C to B with the assistance of tower A.




                    TowersOfHanoi                                                                       Run
             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                              41
Exercise 20.3 GCD
gcd(2, 3) = 1
gcd(2, 10) = 2
gcd(25, 35) = 5
gcd(205, 301) = 5
gcd(m, n)
Approach 1: Brute-force, start from min(n, m) down to 1,
  to check if a number is common divisor for both m and
  n, if so, it is the greatest common divisor.
Approach 2: Euclid’s algorithm
Approach 3: Recursive method
          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         42
Approach 2: Euclid’s algorithm
// Get absolute value of m and n;
t1 = Math.abs(m); t2 = Math.abs(n);
// r is the remainder of t1 divided by t2;
r = t1 % t2;
while (r != 0) {
  t1 = t2;
  t2 = r;
  r = t1 % t2;
}

// When r is 0, t2 is the greatest common
// divisor between t1 and t2
return t2;
        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       43
Approach 3: Recursive Method
gcd(m, n) = n if m % n = 0;
gcd(m, n) = gcd(n, m % n); otherwise;




       Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                            rights reserved.
                                                                                                      44
Fractals?
A fractal is a geometrical figure just like
triangles, circles, and rectangles, but fractals
can be divided into parts, each of which is a
reduced-size copy of the whole. There are
many interesting examples of fractals. This
section introduces a simple fractal, called
Sierpinski triangle, named after a famous
Polish mathematician.

        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       45
Sierpinski Triangle
1.   It begins with an equilateral triangle, which is considered to be
     the Sierpinski fractal of order (or level) 0, as shown in Figure
     (a).
2.   Connect the midpoints of the sides of the triangle of order 0 to
     create a Sierpinski triangle of order 1, as shown in Figure (b).
3.   Leave the center triangle intact. Connect the midpoints of the
     sides of the three other triangles to create a Sierpinski of order
     2, as shown in Figure (c).
4.   You can repeat the same process recursively to create a
     Sierpinski triangle of order 3, 4, ..., and so on, as shown in
     Figure (d).




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           46
Sierpinski Triangle Solution
                                 p1


midBetweenP1P2                                            midBetweenP3P1




     p2                                                             p3

                    midBetweenP2P3



           SierpinskiTriangle                                                                     Run
           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          47
Sierpinski Triangle Solution
                                       p1           Draw the Sierpinski triangle
                                                    displayTriangles(g, order, p1, p2, p3)




            p2                                                   p3




 SierpinskiTriangle                                                                     Run
 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                      rights reserved.
                                                                                                48
Sierpinski Triangle Solution
                                                                    Recursively draw the small Sierpinski triangle
                                                           p1       displayTriangles(g,
                                                                      order - 1, p1, p12, p31)
                                                                    )


Recursively draw the small               p12                              p31
Sierpinski triangle                                                                      Recursively draw the
displayTriangles(g,                                                                      small Sierpinski triangle
   order - 1, p12, p2, p23)                                                              displayTriangles(g,
                                                                                           order - 1, p31, p23, p3)
                               p2                                                     p3 )
                                                          p23




                SierpinskiTriangle                                                                     Run
                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                               49
Recursion vs. Iteration
Recursion is an alternative form of program
control. It is essentially repetition without a loop.

Recursion bears substantial overhead. Each time the
program calls a method, the system must assign
space for all of the method’s local variables and
parameters. This can consume considerable
memory and requires extra time to manage the
additional space.


         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        50
Advantages of Using Recursion
Recursion is good for solving the problems that are
inherently recursive.




         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        51
Tail Recursion
A recursive method is said to be tail recursive if
there are no pending operations to be performed on
return from a recursive call.


  Non-tail recursive                                                ComputeFactorial

  Tail recursive                                   ComputeFactorialTailRecursion



         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        52

More Related Content

What's hot

(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning
(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning
(研究会輪読) Facial Landmark Detection by Deep Multi-task LearningMasahiro Suzuki
 
Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...
Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...
Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...Universitat Politècnica de Catalunya
 
Ai_Project_report
Ai_Project_reportAi_Project_report
Ai_Project_reportRavi Gupta
 
InfoGAN and Generative Adversarial Networks
InfoGAN and Generative Adversarial NetworksInfoGAN and Generative Adversarial Networks
InfoGAN and Generative Adversarial NetworksZak Jost
 
Matching networks for one shot learning
Matching networks for one shot learningMatching networks for one shot learning
Matching networks for one shot learningKazuki Fujikawa
 
Machine Learning for Trading
Machine Learning for TradingMachine Learning for Trading
Machine Learning for TradingLarry Guo
 
Exploiting variable associations to configure efficient local search in large...
Exploiting variable associations to configure efficient local search in large...Exploiting variable associations to configure efficient local search in large...
Exploiting variable associations to configure efficient local search in large...Shunji Umetani
 
Dictionary Learning for Massive Matrix Factorization
Dictionary Learning for Massive Matrix FactorizationDictionary Learning for Massive Matrix Factorization
Dictionary Learning for Massive Matrix Factorizationrecsysfr
 
[DL輪読会]Generative Models of Visually Grounded Imagination
[DL輪読会]Generative Models of Visually Grounded Imagination[DL輪読会]Generative Models of Visually Grounded Imagination
[DL輪読会]Generative Models of Visually Grounded ImaginationDeep Learning JP
 
Generative Adversarial Networks (GAN)
Generative Adversarial Networks (GAN)Generative Adversarial Networks (GAN)
Generative Adversarial Networks (GAN)Manohar Mukku
 
Lesson 27: Integration by Substitution (Section 041 handout)
Lesson 27: Integration by Substitution (Section 041 handout)Lesson 27: Integration by Substitution (Section 041 handout)
Lesson 27: Integration by Substitution (Section 041 handout)Matthew Leingang
 
Graph Kernels for Chemical Informatics
Graph Kernels for Chemical InformaticsGraph Kernels for Chemical Informatics
Graph Kernels for Chemical InformaticsMukund Raj
 
Paper Summary of Disentangling by Factorising (Factor-VAE)
Paper Summary of Disentangling by Factorising (Factor-VAE)Paper Summary of Disentangling by Factorising (Factor-VAE)
Paper Summary of Disentangling by Factorising (Factor-VAE)준식 최
 
Convolutional networks and graph networks through kernels
Convolutional networks and graph networks through kernelsConvolutional networks and graph networks through kernels
Convolutional networks and graph networks through kernelstuxette
 
Mapping the discrete logarithm
Mapping the discrete logarithmMapping the discrete logarithm
Mapping the discrete logarithmJoshua Holden
 
Data-Driven Recommender Systems
Data-Driven Recommender SystemsData-Driven Recommender Systems
Data-Driven Recommender Systemsrecsysfr
 

What's hot (20)

The Perceptron - Xavier Giro-i-Nieto - UPC Barcelona 2018
The Perceptron - Xavier Giro-i-Nieto - UPC Barcelona 2018The Perceptron - Xavier Giro-i-Nieto - UPC Barcelona 2018
The Perceptron - Xavier Giro-i-Nieto - UPC Barcelona 2018
 
Sparse autoencoder
Sparse autoencoderSparse autoencoder
Sparse autoencoder
 
(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning
(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning
(研究会輪読) Facial Landmark Detection by Deep Multi-task Learning
 
Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...
Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...
Deep Generative Models II (DLAI D10L1 2017 UPC Deep Learning for Artificial I...
 
Ai_Project_report
Ai_Project_reportAi_Project_report
Ai_Project_report
 
InfoGAN and Generative Adversarial Networks
InfoGAN and Generative Adversarial NetworksInfoGAN and Generative Adversarial Networks
InfoGAN and Generative Adversarial Networks
 
Recursion in Java
Recursion in JavaRecursion in Java
Recursion in Java
 
Matching networks for one shot learning
Matching networks for one shot learningMatching networks for one shot learning
Matching networks for one shot learning
 
Machine Learning for Trading
Machine Learning for TradingMachine Learning for Trading
Machine Learning for Trading
 
Exploiting variable associations to configure efficient local search in large...
Exploiting variable associations to configure efficient local search in large...Exploiting variable associations to configure efficient local search in large...
Exploiting variable associations to configure efficient local search in large...
 
Dictionary Learning for Massive Matrix Factorization
Dictionary Learning for Massive Matrix FactorizationDictionary Learning for Massive Matrix Factorization
Dictionary Learning for Massive Matrix Factorization
 
[DL輪読会]Generative Models of Visually Grounded Imagination
[DL輪読会]Generative Models of Visually Grounded Imagination[DL輪読会]Generative Models of Visually Grounded Imagination
[DL輪読会]Generative Models of Visually Grounded Imagination
 
Generative Adversarial Networks (GAN)
Generative Adversarial Networks (GAN)Generative Adversarial Networks (GAN)
Generative Adversarial Networks (GAN)
 
Lesson 27: Integration by Substitution (Section 041 handout)
Lesson 27: Integration by Substitution (Section 041 handout)Lesson 27: Integration by Substitution (Section 041 handout)
Lesson 27: Integration by Substitution (Section 041 handout)
 
Curve fitting
Curve fittingCurve fitting
Curve fitting
 
Graph Kernels for Chemical Informatics
Graph Kernels for Chemical InformaticsGraph Kernels for Chemical Informatics
Graph Kernels for Chemical Informatics
 
Paper Summary of Disentangling by Factorising (Factor-VAE)
Paper Summary of Disentangling by Factorising (Factor-VAE)Paper Summary of Disentangling by Factorising (Factor-VAE)
Paper Summary of Disentangling by Factorising (Factor-VAE)
 
Convolutional networks and graph networks through kernels
Convolutional networks and graph networks through kernelsConvolutional networks and graph networks through kernels
Convolutional networks and graph networks through kernels
 
Mapping the discrete logarithm
Mapping the discrete logarithmMapping the discrete logarithm
Mapping the discrete logarithm
 
Data-Driven Recommender Systems
Data-Driven Recommender SystemsData-Driven Recommender Systems
Data-Driven Recommender Systems
 

Viewers also liked

Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8dplunkett
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7dplunkett
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5dplunkett
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9dplunkett
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
First Principles Of Cs Instruction
First Principles Of Cs InstructionFirst Principles Of Cs Instruction
First Principles Of Cs InstructionKatrin Becker
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3dplunkett
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 Bdplunkett
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6dplunkett
 
Ap Power Point Chpt1
Ap Power Point Chpt1Ap Power Point Chpt1
Ap Power Point Chpt1dplunkett
 
Internet principles of operation
Internet principles of operationInternet principles of operation
Internet principles of operationInqilab Patel
 

Viewers also liked (14)

Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
Lecture 4 recursion
Lecture 4    recursionLecture 4    recursion
Lecture 4 recursion
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
First Principles Of Cs Instruction
First Principles Of Cs InstructionFirst Principles Of Cs Instruction
First Principles Of Cs Instruction
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 B
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
 
Ap Power Point Chpt1
Ap Power Point Chpt1Ap Power Point Chpt1
Ap Power Point Chpt1
 
Internet principles of operation
Internet principles of operationInternet principles of operation
Internet principles of operation
 

Similar to JavaYDL20

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptMohammedNouh7
 
Bert pre_training_of_deep_bidirectional_transformers_for_language_understanding
Bert  pre_training_of_deep_bidirectional_transformers_for_language_understandingBert  pre_training_of_deep_bidirectional_transformers_for_language_understanding
Bert pre_training_of_deep_bidirectional_transformers_for_language_understandingThyrixYang1
 

Similar to JavaYDL20 (8)

JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
JavaYDL13
JavaYDL13JavaYDL13
JavaYDL13
 
JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
 
Bert pre_training_of_deep_bidirectional_transformers_for_language_understanding
Bert  pre_training_of_deep_bidirectional_transformers_for_language_understandingBert  pre_training_of_deep_bidirectional_transformers_for_language_understanding
Bert pre_training_of_deep_bidirectional_transformers_for_language_understanding
 
05slide
05slide05slide
05slide
 
03slide
03slide03slide
03slide
 
JavaYDL3
JavaYDL3JavaYDL3
JavaYDL3
 
JavaYDL16
JavaYDL16JavaYDL16
JavaYDL16
 

More from Terry Yoast

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12Terry Yoast
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11Terry Yoast
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08Terry Yoast
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06Terry Yoast
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05Terry Yoast
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04Terry Yoast
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 

More from Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 

JavaYDL20

  • 1. Chapter 20 Recursion Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1
  • 2. Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There are several ways to solve this problem. An intuitive solution is to use recursion by searching the files in the subdirectories recursively. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2
  • 3. Motivations H-trees, depicted in Figure 20.1, are used in a very large- scale integration (VLSI) design as a clock distribution network for routing timing signals to all parts of a chip with equal propagation delays. How do you write a program to display H-trees? A good approach is to use recursion. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3
  • 4. Objectives  To describe what a recursive method is and the benefits of using recursion (§20.1).  To develop recursive methods for recursive mathematical functions (§§20.2– 20.3).  To explain how recursive method calls are handled in a call stack (§§20.2–20.3).  To solve problems using recursion (§20.4).  To use an overloaded helper method to derive a recursive method (§20.5).  To implement a selection sort using recursion (§20.5.1).  To implement a binary search using recursion (§20.5.2).  To get the directory size using recursion (§20.6).  To solve the Towers of Hanoi problem using recursion (§20.7).  To draw fractals using recursion (§20.8).  To discover the relationship and difference between recursion and iteration (§20.9).  To know tail-recursive methods and why they are desirable (§20.10). Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4
  • 5. Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); n! = n * (n-1)! ComputeFactorial Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5
  • 6. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6
  • 7. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7
  • 8. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8
  • 9. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9
  • 10. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10
  • 11. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11
  • 12. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) =3*2 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12
  • 13. animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) = 4 * 3 * ( 2 * ( 1 * 1))) = 4 * 3 * ( 2 * 1) =4*3*2 =4*6 = 24 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13
  • 14. animation Trace Recursive factorial Executes factorial(4) factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14
  • 15. animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 Executes factorial(3) return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15
  • 16. animation Trace Recursive factorial factorial(4) Executes factorial(2) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16
  • 17. animation Trace Recursive factorial factorial(4) Executes factorial(1) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 Space Required for factorial(2) return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17
  • 18. animation Trace Recursive factorial factorial(4) Executes factorial(0) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Space Required Step 3: executes factorial(1) for factorial(1) Step 6: return 1 Space Required for factorial(2) return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18
  • 19. animation Trace Recursive factorial factorial(4) returns 1 Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack Space Required return 2 * factorial(1) for factorial(0) Space Required Step 3: executes factorial(1) for factorial(1) Step 6: return 1 Space Required for factorial(2) return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19
  • 20. animation Trace Recursive factorial factorial(4) returns factorial(0) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Space Required Step 3: executes factorial(1) for factorial(1) Step 6: return 1 Space Required for factorial(2) return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20
  • 21. animation Trace Recursive factorial factorial(4) returns factorial(1) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 Space Required for factorial(2) return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21
  • 22. animation Trace Recursive factorial factorial(4) returns factorial(2) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Space Required for factorial(3) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22
  • 23. animation Trace Recursive factorial factorial(4) returns factorial(3) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 Space Required for factorial(4) return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23
  • 24. animation Trace Recursive factorial returns factorial(4) factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 Stack return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 Main method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24
  • 25. factorial(4) Stack Trace 5 Space Required for factorial(0) 4 Space Required for factorial(1) Space Required for factorial(1) 3 Space Required for factorial(2) Space Required for factorial(2) Space Required for factorial(2) 2 Space Required for factorial(3) Space Required for factorial(3) Space Required for factorial(3) Space Required for factorial(3) 1 Space Required for factorial(4) Space Required for factorial(4) Space Required for factorial(4) Space Required for factorial(4) Space Required for factorial(4) 6 Space Required for factorial(1) Space Required 7 Space Required for factorial(2) for factorial(2) Space Required Space Required 8 Space Required for factorial(3) for factorial(3) for factorial(3) Space Required Space Required Space Required 9 Space Required for factorial(4) for factorial(4) for factorial(4) for factorial(4) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25
  • 26. Other Examples f(0) = 0; f(n) = n + f(n-1); Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26
  • 27. Fibonacci Numbers Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89… indices: 0 1 2 3 4 5 6 7 8 9 10 11 fib(0) = 0; fib(1) = 1; fib(index) = fib(index -1) + fib(index -2); index >=2 fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0) +fib(1) = 1 + fib(1) = 1 + 1 = 2 ComputeFibonacci Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27
  • 28. Fibonnaci Numbers, cont. fib(4) 17: return fib(4) 0: call fib(4) return fib(3) + fib(2) 11: call fib(2) 10: return fib(3) 1: call fib(3) 16: return fib(2) return fib(2) + fib(1) return fib(1) + fib(0) 7: return fib(2) 8: call fib(1) 14: return fib(0) 2: call fib(2) 13: return fib(1) 12: call fib(1) 9: return fib(1) 15: return fib(0) return fib(1) + fib(0) return 1 return 1 return 0 4: return fib(1) 5: call fib(0) 3: call fib(1) return 1 6: return fib(0) return 0 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28
  • 29. Characteristics of Recursion All recursive methods have the following characteristics: – One or more base cases (the simplest case) are used to stop recursion. – Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. In general, to solve a problem using recursion, you break it into subproblems. If a subproblem resembles the original problem, you can apply the same approach to solve the subproblem recursively. This subproblem is almost the same as the original problem in nature with a smaller size. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29
  • 30. Problem Solving Using Recursion Let us consider a simple problem of printing a message for n times. You can break the problem into two subproblems: one is to print the message one time and the other is to print the message for n-1 times. The second problem is the same as the original problem with a smaller size. The base case for the problem is n==0. You can solve this problem using recursion as follows: public static void nPrintln(String message, int times) { if (times >= 1) { System.out.println(message); nPrintln(message, times - 1); } // The base case is times == 0 } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30
  • 31. Think Recursively Many of the problems presented in the early chapters can be solved using recursion if you think recursively. For example, the palindrome problem in Listing 7.1 can be solved recursively as follows: public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case return false; else return isPalindrome(s.substring(1, s.length() - 1)); } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31
  • 32. Recursive Helper Methods The preceding recursive isPalindrome method is not efficient, because it creates a new string for every recursive call. To avoid creating new strings, use a helper method: public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return isPalindrome(s, low + 1, high - 1); } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32
  • 33. Recursive Selection Sort 1. Find the smallest number in the list and swaps it with the first number. 2. Ignore the first number and sort the remaining smaller list recursively. RecursiveSelectionSort Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33
  • 34. Recursive Binary Search 1. Case 1: If the key is less than the middle element, recursively search the key in the first half of the array. 2. Case 2: If the key is equal to the middle element, the search ends with a match. 3. Case 3: If the key is greater than the middle element, recursively search the key in the second half of the array. RecursiveBinarySearch Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34
  • 35. Recursive Implementation /** Use binary search to find the key in the list */ public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return recursiveBinarySearch(list, key, low, high); } /** Use binary search to find the key in the list between list[low] list[high] */ public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35
  • 36. Directory Size The preceding examples can easily be solved without using recursion. This section presents a problem that is difficult to solve without using recursion. The problem is to find the size of a directory. The size of a directory is the sum of the sizes of all files in the directory. A directory may contain subdirectories. Suppose a directory contains files , , ..., , and subdirectories , , ..., , as shown below. directory f1 f2 ... fm d1 d2 ... dn 1 1 1 1 1 1 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36
  • 37. Directory Size The size of the directory can be defined recursively as follows: size( d ) size( f1 ) size( f 2 ) ... size( f m ) size(d1 ) size(d 2 ) ... size( d n ) DirectorySize Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37
  • 38. Towers of Hanoi  There are n disks labeled 1, 2, 3, . . ., n, and three towers labeled A, B, and C.  No disk can be on top of a smaller disk at any time.  All the disks are initially placed on tower A.  Only one disk can be moved at a time, and it must be the top disk on the tower. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38
  • 39. Towers of Hanoi, cont. A B C A B C Original position Step 4: Move disk 3 from A to B A B C A B C Step 1: Move disk 1 from A to B Step 5: Move disk 1 from C to A A B C A B C Step 2: Move disk 2 from A to C Step 6: Move disk 2 from C to B A B C A B C Step 3: Move disk 1 from B to C Step 7: Mve disk 1 from A to B Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39
  • 40. Solution to Towers of Hanoi The Towers of Hanoi problem can be decomposed into three subproblems. n-1 disks n-1 disks . . . . . . A B C A B C Original position Step2: Move disk n from A to C n-1 disks n-1 disks . . . . . . A B C A B C Step 1: Move the first n-1 disks from A to C recursively Step3: Move n-1 disks from C to B recursively Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40
  • 41. Solution to Towers of Hanoi  Move the first n - 1 disks from A to C with the assistance of tower B.  Move disk n from A to B.  Move n - 1 disks from C to B with the assistance of tower A. TowersOfHanoi Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 41
  • 42. Exercise 20.3 GCD gcd(2, 3) = 1 gcd(2, 10) = 2 gcd(25, 35) = 5 gcd(205, 301) = 5 gcd(m, n) Approach 1: Brute-force, start from min(n, m) down to 1, to check if a number is common divisor for both m and n, if so, it is the greatest common divisor. Approach 2: Euclid’s algorithm Approach 3: Recursive method Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 42
  • 43. Approach 2: Euclid’s algorithm // Get absolute value of m and n; t1 = Math.abs(m); t2 = Math.abs(n); // r is the remainder of t1 divided by t2; r = t1 % t2; while (r != 0) { t1 = t2; t2 = r; r = t1 % t2; } // When r is 0, t2 is the greatest common // divisor between t1 and t2 return t2; Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 43
  • 44. Approach 3: Recursive Method gcd(m, n) = n if m % n = 0; gcd(m, n) = gcd(n, m % n); otherwise; Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 44
  • 45. Fractals? A fractal is a geometrical figure just like triangles, circles, and rectangles, but fractals can be divided into parts, each of which is a reduced-size copy of the whole. There are many interesting examples of fractals. This section introduces a simple fractal, called Sierpinski triangle, named after a famous Polish mathematician. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 45
  • 46. Sierpinski Triangle 1. It begins with an equilateral triangle, which is considered to be the Sierpinski fractal of order (or level) 0, as shown in Figure (a). 2. Connect the midpoints of the sides of the triangle of order 0 to create a Sierpinski triangle of order 1, as shown in Figure (b). 3. Leave the center triangle intact. Connect the midpoints of the sides of the three other triangles to create a Sierpinski of order 2, as shown in Figure (c). 4. You can repeat the same process recursively to create a Sierpinski triangle of order 3, 4, ..., and so on, as shown in Figure (d). Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 46
  • 47. Sierpinski Triangle Solution p1 midBetweenP1P2 midBetweenP3P1 p2 p3 midBetweenP2P3 SierpinskiTriangle Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 47
  • 48. Sierpinski Triangle Solution p1 Draw the Sierpinski triangle displayTriangles(g, order, p1, p2, p3) p2 p3 SierpinskiTriangle Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 48
  • 49. Sierpinski Triangle Solution Recursively draw the small Sierpinski triangle p1 displayTriangles(g, order - 1, p1, p12, p31) ) Recursively draw the small p12 p31 Sierpinski triangle Recursively draw the displayTriangles(g, small Sierpinski triangle order - 1, p12, p2, p23) displayTriangles(g, order - 1, p31, p23, p3) p2 p3 ) p23 SierpinskiTriangle Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 49
  • 50. Recursion vs. Iteration Recursion is an alternative form of program control. It is essentially repetition without a loop. Recursion bears substantial overhead. Each time the program calls a method, the system must assign space for all of the method’s local variables and parameters. This can consume considerable memory and requires extra time to manage the additional space. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 50
  • 51. Advantages of Using Recursion Recursion is good for solving the problems that are inherently recursive. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 51
  • 52. Tail Recursion A recursive method is said to be tail recursive if there are no pending operations to be performed on return from a recursive call. Non-tail recursive ComputeFactorial Tail recursive ComputeFactorialTailRecursion Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 52