Recursion Liang Introduction to Java Programming Eighth Edition
- Slides: 62
Recursion Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2
Motivations The Eight Queens puzzle is to place eight queens on a chessboard such that no two queens are on the same row, same column, or same diagonal. How do you write a program to solve this problem? A good approach to solve this problem is to use recursion. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3
What is recursive method? FA method that calls itself F With each method call the problem becomes simpler F Must have a condition that leads to the method no longer making another call on itself Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4
Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); 0!=1 1!=1 2!=2*1!=2 3!=3*2=6 …. n! = n * (n-1)! Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5
animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6
animation Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); factorial(3) = 3 * factorial(2) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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 =6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 13
animation Trace Recursive factorial Executes factorial(4) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14
animation Trace Recursive factorial Executes factorial(3) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15
animation Trace Recursive factorial Executes factorial(2) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16
animation Trace Recursive factorial Executes factorial(1) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17
animation Trace Recursive factorial Executes factorial(0) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18
animation Trace Recursive factorial returns 1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19
animation Trace Recursive factorial returns factorial(0) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20
animation Trace Recursive factorial returns factorial(1) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21
animation Trace Recursive factorial returns factorial(2) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22
animation Trace Recursive factorial returns factorial(3) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23
animation Trace Recursive factorial returns factorial(4) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24
factorial(4) Stack Trace Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25
Factorial public static long factorial(int n) { System. out. println( "Method" + n ); if (n == 0){ // Base case System. out. println( "Returned 1" ); return 1; }else{ long result = n * factorial(n - 1); // Recursive call System. out. print( "Returned " + result); System. out. println( " : " + n + " * factorial("+ n + "-1)" ); return result; } } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26
Infinite Recursion public static long factorial(int n) { return result = n * factorial(n - 1); // Recursive call } Stack over flow error Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 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 + 1 = 2 A model to show the growth of rabbit population Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28
Fibonnaci Numbers, cont. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29
Fibonnaci Numbers, cont. static int count; /** The method for finding the Fibonacci number */ public static long fib(long index) { System. out. print(count++); System. out. println(": call fib( " + index +")" ); if (index == 0){ // Base case System. out. print(count++); System. out. println(" : Returned 0 "); return 0; }else if (index == 1){ // Base case System. out. print(count++); System. out. println(" : Returned 1 "); return 1; }else{ // Reduction and recursive calls long result = fib(index - 1) + fib(index - 2); System. out. print(count++); System. out. println( ": Returned fib(" + index-- + ")"); return result; } } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30
Case Study: Non-recursive version of Fibonacci public long static long fib(long n) { f 0 = 0; // For fib(0) f 1 = 1; // For fib(1) f 2 = 1; // For fib(2) if (n == 0) return f 0; else if (n == 1) return f 1; else if (n == 2) return f 2; Obviously, the complexity of this new algorithm is. This is a tremendous improvement over the recursive algorithm. This is known as dynamic programming. for (int i = 3; i <= n; i++) { f 0 = f 1; f 1 = f 2; f 2 = f 0 + f 1; } return f 2; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31
Dynamic programming F Process of solving subproblems, then combine the solutions to obtain an overall result. F This naturally leads to a recursive solution. – Sometimes it is not efficient to use recursions, because subproblems overlap. – The key idea behind dynamic programming is to solve each subproblem only once and store the results for later use and avoid redundant computing. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32
f 0 f 1 f 2 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 f 0 f 1 f 2 Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89… indices: 0 4 5 6 7 8 f 0 f 1 f 2 1 1 2 3 5 8 13 21 34 55 89… 1 5 6 7 8 9 10 11 Fibonacci series: 0 indices: 0 1 2 2 3 3 4 9 10 11 Fibonacci series: 0 1 1 2 3 5 8 f 0 f 1 f 2 13 21 34 55 89… indices: 0 1 2 3 4 5 6 7 8 9 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 10 11 33
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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34
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 n. Println(String message, int times) { if (times >= 1) { System. out. println(message); n. Println(message, times - 1); } // The base case is times == 0 } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35
Output for n. Println(“hello”, 3) 3>1 => hello n. Println(“hello”, 2) 2>1 => hello n. Println(“hello”, 1) 1==1 => hello n. Println(“hello”, 0) 0<1. STOP Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36
Think Recursively The is. Palindrome problem approach 1 public static boolean is. Palindrome(String s) { int low = 0; int high = s. length() – 1; Boolean is. Palindrome = true; While(low<high){ if(s. char. At(low) != s. char. At(high)){ is. Palindrome=false; break; } low++; high--; } Return is. Palindrome; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37
Think Recursively Many problems can be solved using recursion if you think recursively. For example, the palindrome problem approach 2 public static boolean is. Palindrome(String s) { if (s. length() <= 1) // Base case return true; else if (s. char. At(0) != s. char. At(s. length() - 1)) // Base case return false; else return is. Palindrome(s. substring(1, s. length() - 1)); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38
Recursive Helper Methods The preceding recursive is. Palindrome 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 is. Palindrome(String s) { return is. Palindrome(s, 0, s. length() - 1); } public static boolean is. Palindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s. char. At(low) != s. char. At(high)) // Base case return false; else return is. Palindrome(s, low + 1, high - 1); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39
Binary Search public static int binary. Search(int[] list, int key) { int low = 0; int high = list. length - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } return -1 - low; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40
Recursive Binary Search 1. 2. 3. Case 1: If the key is less than the middle element, recursively search the key in the first half of the array. Case 2: If the key is equal to the middle element, the search ends with a match. Case 3: If the key is greater than the middle element, recursively search the key in the second half of the array. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41
Recursive Implementation /** Use binary search to find the key in the list */ public static int recursive. Binary. Search(int[] list, int key) { int low = 0; int high = list. length - 1; return recursive. Binary. Search(list, key, low, high); } /** Use binary search to find the key in the list between list[low] list[high] */ public static int recursive. Binary. Search(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 recursive. Binary. Search(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursive. Binary. Search(list, key, mid + 1, high); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42
GCD: Greatest Common Divisor gcd(2, 3) = 1 gcd(2, 10) = 2 gcd(25, 35) = 5 gcd(205, 301) = 5 gcd(m, n) Approach 1: Brute-force Approach 2: Euclid’s algorithm Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43
Case Study: GCD Algorithms Version 1 public static int gcd(int m, int n) { int gcd = 1; for (int k = 2; k <= m && k <= n; k++) { if (m % k == 0 && n % k == 0) gcd = k; } return gcd; } Obviously, the complexity of this algorithm is. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44
Case Study: GCD Algorithms Version 2 for (int k = n; k >= 1; k--) { if (m % k == 0 && n % k == 0) { gcd = k; break; } } Assume m>=n The worst-case time complexity of this algorithm is still. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45
Case Study: GCD Algorithms Version 3 public static int gcd(int m, int n) { int gcd = 1; if (m == n) return m; for (int k = n / 2; k >= 1; k--) { if (m % k == 0 && n % k == 0) { gcd = k; break; } } It is proved that a divisor for n can not be greater than n/2. so we can start from n/2 rather than n. return gcd; } The worst-case time complexity of this algorithm is still. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46
Euclid’s algorithm Let gcd(m, n) denote the gcd for integers m and n: FIf m % n is 0, gcd (m, n) is n. FOtherwise, gcd(m, n) is gcd(n, m % n). m = n*k + r if p is divisible by both m and n m / p = n*k/p + r/p Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47
Euclid’s Algorithm Implementation public static int gcd(int m, int n) { if (m % n == 0) return n; else return gcd(n, m % n); } The time complexity of this algorithm is O(logn). Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48
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. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49
Directory Size The size of the directory can be defined recursively as follows: Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50
Towers of Hanoi F There are n disks labeled 1, 2, 3, . . . , n, and three towers labeled A, B, and C. F No disk can be on top of a smaller disk at any time. F All the disks are initially placed on tower A. F Only one disk can be moved at a time, and it must be the top disk on the tower. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51
Towers of Hanoi, cont. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52
Solution to Towers of Hanoi The Towers of Hanoi problem can be decomposed into three subproblems. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 53
Solution to Towers of Hanoi F F F 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. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 54
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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55
Sierpinski Triangle 1. 2. 3. 4. It begins with an equilateral triangle, which is considered to be the Sierpinski fractal of order (or level) 0, as shown in Figure (a). 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). 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). 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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 56
Sierpinski Triangle Solution Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 57
Eight Queens (Homework 3) The Eight Queens puzzle is to place eight queens on a chessboard such that no two queens are on the same row, same column, or same diagonal. A good approach to solve this problem is to use recursion. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 58
Eight Queens (Homework 3) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 59
Questions? Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 60
Case Study: Fibonacci Numbers /** The method for finding the Fibonacci number */ public static long fib(long index) { if (index == 0) // Base case return 0; else if (index == 1) // Base case return 1; else // Reduction and recursive calls return fib(index - 1) + fib(index - 2); } Finonacci 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) =Liang, fib(index -1)Programming, + fib(index >=2 Inc. All Introduction to Java Eighth Edition, -2); (c) 2011 index Pearson Education, rights reserved. 0132130807 61
Complexity for Recursive Fibonacci Numbers Since and Therefore, the recursive Fibonacci method takes. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 62
- Elementary programming in java
- Introduction to java programming 10th edition quizzes
- Psychology eighth edition david g myers
- Psychology
- Operations management eighth edition
- Liang fontdemo.java
- Liang fontdemo.java
- To understand recursion you must understand recursion
- Java programming enterprise edition course
- Recursion vs dynamic programming
- Dynamic programming recursion example
- Dynamic programming recursion example
- Java introduction to problem solving and programming
- Java introduction to problem solving and programming
- Java introduction to problem solving and programming
- Tail recursive
- Recursion in java
- Small n design
- Tail recursion
- Recursion
- Handshake problem formula
- What is recursion
- Recursive definition
- Recursion java
- Anagram of eighth
- Matching planet rings
- Nearest eighth of an inch
- The fifth, sixth, seventh, and eighth amendments protect *
- What is the eighth commandment catholic
- Katja mahal
- Anterior three quarter crown
- Eighth amendment excessive bail
- Eighth letter of the alphabet
- Criminal justice lesson
- 9th amendment meaning
- Richard seow yung liang
- Zhuo shi wo li liang
- Zhong han liang
- Yuanxing liang
- Amber liang
- Mengkode arsip adalah
- Randy liang
- David teo choon liang
- How was ma liang like?
- Zong-liang yang
- Liang jianhui
- Nba schedule maker
- Chia liang cheng
- Otk keuangan kelas 11
- Liang zhu umbc
- Zong-liang yang
- Siemens sans bold
- Dr liang hao nan
- Pengertian arsip menurut the liang gie
- Patrick liang
- Kathleen liang
- Edmund liang
- Cakera dwicekung
- Bob liang
- Diana liang faa
- Foo joon liang
- Cs106b lectures
- Mis chapter 6