Presentation is loading. Please wait.

Presentation is loading. Please wait.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 1 Chapter 15 Recursive Algorithms (from the publisher’s.

Similar presentations


Presentation on theme: "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 1 Chapter 15 Recursive Algorithms (from the publisher’s."— Presentation transcript:

1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 1 Chapter 15 Recursive Algorithms (from the publisher’s notes, but mostly from tantc)

2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 2 Objectives After you have read and studied this chapter, you should be able to  To learn to think recursively.  Develop an understanding and appreciation of recursive problem solving.  Learn to use recursion in Java to solve problems.  Develop an appreciation of the trade-offs between recursion and iteration.

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 3 Basic

4 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 4 What is Recursion? (1/2) To perform a task T by performing some similar smaller task(s) T’. Example: –Formula for factorial: n! = n * (n-1) * (n-2) * … * 2 * 1 for n > 0 0! = 1 –Recursive formula for factorial: n! = n * (n–1)! for n>0 0! = 1 (Examples: 3! = 6; 4! = 24; 7! = 5040)

5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 5 What is Recursion? (2/2) The idea behind recursion is similar to PMI (Principle of Mathematical Induction). Example: Prove the recursive formula for factorial. –Basis: 0! = 1 –Induction hypothesis: Assume that the recursive formula is true for x > 0. –Inductive step: (x + 1)! = (x + 1) * x * (x – 1) * … * 1 = (x + 1) * x!

6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 6 Recursive Definitions A definition that defines something in terms of itself is called a recursive definition. –The descendants of a person are the person’s children and all of the descendants of the person’s children. –A list of numbers is a number or a number followed by a comma and a list of numbers. A recursive algorithm is an algorithm that invokes itself to solve smaller or simpler instances of a problem instances. –The factorial of a number n is: n times the factorial of n-1.

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 7 Example 1. Counting occurrences of Character

8 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 8 Count Occurrences of Character (1/4) Mississippi sassafras We want countChar('s', "Mississippi sassafras") to return the value of 8. Recursive thinking goes... If I could just get someone to count the s’s in this smaller string… … then the number of s’s is either that number or 1 more, depending on whether the first letter is an s.

9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 9 Count Occurrences of Character (2/4) // count the number of occurrences // of character ch in string str. public static int countChar(char ch, String str) { int ans; if (str.length() == 0) // base case ans = 0; else if (str.charAt(0) == ch) ans = 1 + countChar(ch, str.substring(1)); else ans = countChar(ch, str.substring(1)); return ans; }

10 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 10 Count Occurrences of Character (3/4) public static int countChar(char ch, String str) { if (str.length() == 0) // base case return 0; else if (str.charAt(0) == ch) return 1 + countChar(ch, str.substring(1)); else return countChar(ch, str.substring(1)); } or

11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 11 Count Occurrences of Character (4/4) public static int countChar(char ch, String str) { int ans = 0; for (int i = 0; i < str.length(); ++i) { if (str.charAt(i) == ch) ++ans; } return ans; } Compare with iterative version:

12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 12 Example 2. Factorial

13 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 13 Factorial: Definition An imprecise definition A precise definition

14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 14 Recursive Methods A recursive method generally has two parts. –A termination part that stops the recursion. This is called the base case (or anchor case). The base case should have a simple or trivial solution. –One or more recursive calls. This is called the recursive case. The recursive case calls the same method but with simpler or smaller arguments. if ( base case satisfied ) { return value; } else { make simpler recursive call(s); }

15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 15 factorial() (1/2) public static int factorial(n) { if (n == 0) return 1; else return n * factorial(n-1); } Base case. Recursive case deals with a simpler (smaller) version of the same task.

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 16 factorial() (2/2) public static int factorial(n) { if (n == 0) return 1; else return n * factorial(n-1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); int nfactorial = factorial(number); System.out.println(number + "! = " + nfactorial); }

17 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 17 Factorial: Recursive Invocation A new activation record is created for every method invocation –Including recursive invocations main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * factorial(n-1);n = 1factorial()return n * factorial(n-1); n = 0factorial()return 1;

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 18 Factorial: Result Passing (1/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * factorial(n-1); n = 1factorial()return n * factorial(n-1); n = 0factorial()return 1;

19 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 19 Factorial: Result Passing (2/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * factorial(n-1); n = 1factorial()return n * factorial(n-1); n = 0factorial()return 1;

20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 20 Factorial: Result Passing (3/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * factorial(n-1); n = 1factorial()return n * 1;

21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 21 Factorial: Result Passing (4/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * factorial(n-1); n = 1factorial()return 1 * 1;

22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 22 Factorial: Result Passing (5/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * factorial(n-1); n = 1factorial()return 1 * 1;

23 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 23 Factorial: Result Passing (6/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return n * 1;

24 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 24 Factorial: Result Passing (7/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return 2 * 1;

25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 25 Factorial: Result Passing (8/12) main()int nfactorial = factorial(n); n = 3factorial()return n * factorial(n-1); n = 2factorial()return 2 * 1;

26 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 26 Factorial: Result Passing (9/12) main()int nfactorial = factorial(n); n = 3factorial()return n * 2;

27 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 27 Factorial: Result Passing (10/12) main()int nfactorial = factorial(n); n = 3factorial()return 3 * 2;

28 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 28 Factorial: Result Passing (11/12) main()int nfactorial = factorial(n); n = 3factorial()return 3 * 2;

29 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 29 Factorial: Result Passing (12/12) main()int nfactorial = 6;

30 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 30 Infinite Recursion A common programming error when using recursion is to not stop making recursive calls. –The program will continue to recurse until it runs out of memory. –Be sure that your recursive calls are made with simpler or smaller subproblems, and that your algorithm has a base case that terminates the recursion. –Avoid redundant base case: public static int factorial(n) { if (n == 0) return 1; else if (n == 1) return 1; else return n * factorial(n-1); }

31 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 31 Example 3. Sum of Squares

32 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 32 Computing Sum of Squares (1/5) Given 2 positive integers m and n, where m ≤ n, compute: sumSquares(m, n) = m 2 + (m+1) 2 + … + n 2 Example: sumSquares(5, 10) = 5 2 + 6 2 + 7 2 + 8 2 + 9 2 + 10 2 = 355

33 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 33 Computing Sum of Squares (2/5) ‘Going-up’ recursion: ‘Going-down’ recursion: public static int sumSquares (int m, int n) { if (m == n) return m * m; else return m*m + sumSquares(m+1, n); } public static int sumSquares (int m, int n) { if (m == n) return n * n; else return n*n + sumSquares(m, n-1); }

34 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 34 Computing Sum of Squares (3/5) ‘Combining two half-solutions’ recursion: public static int sumSquares (int m, int n) { if (m == n) return m * m; else { int middle = (m + n)/2; return sumSquares(m, middle) + sumSquares(middle+1, n); }

35 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 35 Computing Sum of Squares (4/5) Call trees for ‘going-up’ and ‘going-down’ versions. sumSquares(5,10) sumSquares(6,10) sumSquares(7,10) sumSquares(8,10) sumSquares(9,10) sumSquares(10,10) 100 + 81 181 + 64 245 + 49 294 + 36 330 + 25 355 sumSquares(5,10) sumSquares(5,9) sumSquares(5,8) sumSquares(5,7) sumSquares(5,6) sumSquares(5,5) 25 + 36 61 + 49 110 + 64 174 + 81 255 + 100 355

36 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 36 Computing Sum of Squares (5/5) Call tree for ‘combining two half-solutions’ version. sumSquares(5,10) sumSquares(8,10) sumSq(5,6) 25 245 355 sumSquares(5,7) sumSq(7,7)sumSq(8,9)sumSq(10,10) sumSq(5,5)sumSq(6,6) 36 2536 61 49 110 64 sumSq(8,8)sumSq(9,9) 81 6481 145100

37 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 37 Example 4. GCD

38 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 38 Computing GCD (1/7) Greatest common divisor (GCD) of two non-negative integers (not both zero). + // Compute GCD of two non-negative integers // m and n, not both zero, using recursion. public static int gcd (int m, int n) { if (n == 0) return m; else return gcd(n, m % n); }

39 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 39 Computing GCD (2/7) Trace gcd(539, 84) gcd(539, 84) gcd(84, 35) gcd(35, 14) gcd(14, 7) gcd(7, 0) public static int gcd(int m, int n) { if (n == 0) return m; else return gcd(n, m % n); }

40 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 40 Computing GCD (3/7) Trace gcd(539, 84) public static int gcd(int m, int n) { if (n == 0) return m; else return gcd(n, m % n); } gcd(539, 84) gcd(84, 35) gcd(35, 14) gcd(14, 7) gcd(7, 0) 7

41 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 41 Computing GCD (4/7) Trace gcd(539, 84) public static int gcd(int m, int n) { if (n == 0) return m; else return gcd(n, m % n); } gcd(539, 84) gcd(84, 35) gcd(35, 14) gcd(14, 7) 7

42 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 42 Computing GCD (5/7) Trace gcd(539, 84) public static int gcd(int m, int n) { if (n == 0) return m; else return gcd(n, m % n); } gcd(539, 84) gcd(84, 35) gcd(35, 14) 7

43 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 43 Computing GCD (6/7) Trace gcd(539, 84) public static int gcd(int m, int n) { if (n == 0) return m; else return gcd(n, m % n); } gcd(539, 84) gcd(84, 35) 7

44 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 44 Computing GCD (7/7) Trace gcd(539, 84) public static int gcd(int m, int n) { if (n == 0) return m; else return gcd(n, m % n); } gcd(539, 84) 7

45 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 45 Example 5. Fibonacci Numbers

46 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 46 Fibonacci Numbers (1/5) Developed by Leonardo Pisano in 1202. –Investigating how fast rabbits could breed under idealized circumstances. –Assumptions A pair of male and female rabbits always breed and produce another pair of male and female rabbits. A rabbit becomes sexually mature after one month, and that the gestation period is also one month. –Pisano wanted to know the answer to the question how many rabbits would there be after one year?

47 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 47 Fibonacci Numbers (2/5) The sequence generated is: 1, 1, 2, 3, 5, 8, 13, 21, 34, … Some version starts with 0: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … The number of pairs for a month is the sum of the number of pairs in the two previous months.

48 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 48 Fibonacci Numbers (3/5) What is the equation for Fibonacci sequence? +

49 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 49 Fibonacci Numbers (4/5) // Version 1: 0, 1, 1, 2, 3, 5, 8, 13, 21,... public static int fibonacci (int n) { if (n <= 1) return n; else return fibonacci(n-1) + fibonacci(n-2); } // Version 2: 1, 1, 2, 3, 5, 8, 13, 21, 34,... public static int fibonacci (int n) { if (n <= 2) return 1; else return fibonacci(n-1) + fibonacci(n-2); }

50 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 50 Fibonacci Numbers (5/5) Fibonacci(5) Fibonacci(4)Fibonacci(3) Fibonacci(2)Fibonacci(3)Fibonacci(2)Fibonacci(1) Fibonacci(2)Fibonacci(1) 32 21 11 11 5

51 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 51 Tracing Recursive Codes & Recursion vs Iteration

52 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 52 Tracing Recursive Codes (1/2) Beginners usually rely on tracing to understand the sequence of recursive calls and the passing back of results. Tail recursion is one in which the recursive call is the last operation in the code. –Examples encountered that are tail-recursive: factorial, sum of squares (‘going-up’ and ‘going-down’ versions), GCD. –Examples that are not tail-recursive: sum of squares (‘combining two half-solutions’ version), Fibonacci sequence. However, tracing a recursive code is tedious, especially for non-tail- recursive codes. The call tree could be huge (example: Fibonacci.)

53 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 53 Tracing Recursive Codes (2/2) If tracing is needed to aid understanding, start tracing with small problem sizes, then gradually see the relationship between the successive calls. Students should grow out of tracing and understand recursion by examining the relationship between the problem and its immediate subproblem(s).

54 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 54 Notes It is not typical to write a recursive main() method. Besides direct recursion, there could be mutual or indirect recursion –Examples: Method A calls method B, which calls method A. Method X calls method Y, which calls method Z, which calls method X. Sometimes, auxiliary subroutines are needed to implement recursion. The inherent nature of recursion gives rise to a ‘loop’ structure. At this point, most problem can be solved with such simple recursion. Recursion in a loop (or nested loops) is only needed for more advanced problems.

55 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 55 Recursion versus Iteration (1/2) Iteration can be more efficient –Replaces method calls with looping –Less memory is used (no activation record for each call) Some good compilers are able to transform a tail-recursion code into an iterative code. If a problem can be done easily with iteration, then do it with iteration. –For example, Fibonacci can be coded with iteration or recursion, but the recursive version is very inefficient (large call tree), so use iteration instead. (Can you write an iterative version for Fibonacci?) –Additional technique (such as memoization) could be used to improve efficiency – covered in advance course.

56 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 56 Recursion versus Iteration (2/2) Many problems are more naturally solved with recursion, which can provide elegant solution. –Towers of Hanoi –Mergesort Conclusion: choice depends on problem and the solution context. In general, use recursion if –A recursive solution is natural and easy to understand. –A recursive soluition does not result in excessive duplicate computation. –The equivalent iterative solution is too complex.

57 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 57 Example 6. Tower of Hanoi

58 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 58 Towers of Hanoi (1/12) This classical “Towers of Hanoi” puzzle has attracted the attention of computer scientists more than any other puzzles. Invented by Edouard Lucas, a French mathematician, in1883. There are 3 poles (A, B and C) and a tower of disks on the first pole A, with the smallest disk on the top and the biggest at the bottom. The purpose of the puzzle is to move the whole tower from pole A to pole C, with the following simple rules: –Only one disk can be moved at a time. –A bigger disk must not rest on a smaller disk.

59 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 59 Towers of Hanoi (2/12) Legend: –In the great temple of Brahma in Benares, on a brass plate under the dome that marks the center of the world, there are 64 disks of pure gold that the priests carry one at a time between these diamond needles according to Brahma's immutable law: No disk may be placed on a smaller disk. In the begging of the world all 64 disks formed the Tower of Brahma on one needle. Now, however, the process of transfer of the tower from one needle to another is in mid course. When the last disk is finally in place, once again forming the Tower of Brahma but on a different needle, then will come the end of the world and all will turn to dust. –Reference: R. Douglas Hofstadter. Metamagical themas. Scientific American, 248(2):16-22, March 1983.

60 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 60 Towers of Hanoi (3/12) We attempt to write a produce to produce instructions on how to move the disks from pole A to pole C to complete the puzzle. Example: A tower with 3 disks. Output produced by program is as followed. It is assumed that only the top disk can be moved. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C

61 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 61 Towers of Hanoi (4/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

62 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 62 Towers of Hanoi (5/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

63 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 63 Towers of Hanoi (6/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

64 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 64 Towers of Hanoi (7/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

65 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 65 Towers of Hanoi (8/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

66 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 66 Towers of Hanoi (9/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

67 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 67 Towers of Hanoi (10/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC

68 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 68 Towers of Hanoi (11/12) Example: A tower with 3 disks. Move disk from A to C Move disk from A to B Move disk from C to B Move disk from A to C Move disk from B to A Move disk from B to C Move disk from A to C ABC VIOLA!

69 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 69 Towers of Hanoi (12/12) public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print( "Enter number of disks: " ); int disks = scanner.nextInt(); towers(disks, 'A', 'B', 'C'); } + public static void towers(int n, char source, char temp, char dest) { if (n > 0) { towers(n-1, source, dest, temp); System.out.println("Move disk from " + source + " to " + dest); towers(n-1, temp, source, dest); }

70 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 70 Example 7. Binary Search

71 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 71 Binary Search (1/6) Compare the search value to the middle element of the list. If the search value matches the middle element, the desired value has been located and the search is over. If the search value doesn’t match, then if it is in the list it must be either to the left or right of the middle element. The correct sublist can be searched using the same strategy – divide and conquer.

72 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 72 Binary Search (2/6) data 36128172032213345 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Compare search value to this element. If the search value matches, the search is successful. If the search value is less than this element (data[4]), then the search value, if it is in the list, must be to the left of data[4]. If the search value is greater than this element (data[4]), then if it is in the list, it must be to the right of data[4].

73 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 73 Binary Search (3/6) Example: Search for 20 in this list data 36128172032213345 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Go to middle of list. Compare this element with our search value. 17 is smaller than 20, so left half is ignored. Go to middle of remaining list. Compare this element with our search value. Found! Go to middle of remaining list. Compare this element with our search value. 32 is larger than 20, so right half is ignored.

74 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 74 Binary Search (4/6) Iterative version: // binarySearch(): examine sorted list for a key public static int binarySearch(int[] data, int key) { int left = 0; int right = data.length – 1; while (left <= right) { int mid = (left + right)/2; if (data[mid] == key) return mid; else if (data[mid] < key) left = mid + 1; else right = mid – 1; } return -1; }

75 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 75 Binary Search (5/6) Recursive version: + // recursive version public static int binarySearch(int[] data, int key, int left, int right) { if (left > right) return -1; else { int mid = (left + right)/2; if (key == data[mid]) return mid; else if (key < data[mid]) return binarySearch(data, key, left, mid - 1); else return binarySearch(data, key, mid + 1, right); }

76 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 76 Binary Search (6/6) Calling the recursive binary search method. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] intArray = {3, 6, 8, 12, 17, 20, 21, 32, 33, 45}; System.out.print("Enter search key: "); int searchKey = scanner.nextInt(); int index = binarysearch(intArray, searchKey, 0, intArray.length - 1); System.out.println("Key found at index " + index); }

77 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 77 Efficiency of Binary Search Height of a binary tree is the worst case number of comparisons needed to search a list. Tree containing 31 nodes has a height of 5. In general, a tree with n nodes has a height of log 2 (n+1). Searching a list with a billion nodes only requires 31 comparisons. Binary search is efficient!

78 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 78 Example 7. Recursion on data structures

79 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 79 Recursion on Data Structures Besides using recursion to compute numerical values (factorial, Fibonacci numbers, etc.), recursion is also useful for processing on data structures (example: arrays). Examples: –Binary search on a sorted array. –Finding maximum or minimum value in an array. –Finding a path through the maze. –And many others… Some of the more complex problems belong to a more advanced course, but we shall look at some simpler problems.

80 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 80 Reversing an Array // reverse an integer array public static void reverse (int[] array, int start, int finish) { if (start < finish) { int temp = array[start]; array[start] = array[finish]; array[finish] = temp; reverse (array, start+1, finish-1); } public static void main(String[] args) { int[] intArray = { 3, 7, 1, 4, 12, 9, 7, 5 }; reverse (intArray, 0, intArray.length-1); }

81 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 81 Auxiliary Subroutines (1/3) Sometimes, for some reasons (say coupling), you may be given a fixed signature of a method and asked to devise a recursive code for it. –Example: Reverse a list void reverse (int[] array) –Example: Binary search void binarySearch (int[] data, int key) In this case, you would need to write auxiliary method(s).

82 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 82 Auxiliary Subroutines (2/3) Reversing a list // reverse an integer array public static void reverse (int[] array) { reverseAux (array, 0, array.length-1); } // reverse an integer array private static void reverseAux (int[] array, int start, int finish) { if (start < finish) { int temp = array[start]; array[start] = array[finish]; array[finish] = temp; reverseAux (array, start+1, finish-1); }

83 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 83 Auxiliary Subroutines (3/3) The call to reverse() method is then simplified as follows. –Note that this does not require the caller to provide the starting and ending indices as in the previous version. This reduces coupling. –Note that the auxiliary method reverseAux() is declared as private, since it is only to be called by the reverse() method and not by any other methods. –Note also that the auxiliary method could also be named reverse(), since Java allows method overloading. public static void main(String[] args) { int[] intArray = { 3, 7, 1, 4, 12, 9, 7, 5 }; reverse (intArray); }

84 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 84 Example 8. Directory Listing

85 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 85 Directory Listing List the names of all files in a given directory and its subdirectories. public void directoryListing(File dir) { //assumption: dir represents a directory String[] fileList = dir.list(); //get the contents String dirPath = dir.getAbsolutePath(); for (int i = 0; i < fileList.length; i++) { File file = new File(dirPath + "/" + fileList[i]); if (file.isFile()) { //it's a file System.out.println( file.getName() ); } else { directoryListing( file ); //it's a directory } //so make a } //recursive call } Recursive case End case Test

86 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 86 Example 9. Anagram

87 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 87 Anagram List all anagrams of a given word. Word C A T C T A A T C A C T T C A T A C Anagrams

88 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 88 Anagram Solution The basic idea is to make recursive calls on a sub-word after every rotation. Here’s how: C C A A T T Recursion A A T T C C T T C C A A Rotate Left C A T C T A A T C A C T T C A T A C

89 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 89 Anagram Method End case Test Recursive case public void anagram( String prefix, String suffix ) { String newPrefix, newSuffix; int numOfChars = suffix.length(); if (numOfChars == 1) { //End case: print out one anagram System.out.println( prefix + suffix ); } else { for (int i = 1; i <= numOfChars; i++ ) { newSuffix = suffix.substring(1, numOfChars); newPrefix = prefix + suffix.charAt(0); anagram( newPrefix, newSuffix ); //recursive call //rotate left to create a rearranged suffix suffix = newSuffix + suffix.charAt(0); }

90 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 90 End of Lecture #15


Download ppt "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 15 - 1 Chapter 15 Recursive Algorithms (from the publisher’s."

Similar presentations


Ads by Google