1 / 93

Recursion

Recursion. Chapter 5. Chapter Objectives. T hink recursively T race a recursive method W rite recursive algorithms Apply Recursion to solving problems LinkedList class recursive data structures recursive methods. Recursion. What is Recursion? Applications:

louisa
Download Presentation

Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Recursion Chapter 5

  2. Chapter Objectives • Think recursively • Trace a recursive method • Write recursive algorithms • Apply Recursion to solving problems • LinkedListclass • recursive data structures • recursive methods

  3. Recursion • What is Recursion? • Applications: • AIexhibit intelligent behavior: • compute factorials • compute GCD • process data structures • search efficiently • find a path through a maze, and • …

  4. Recursive Thinking Section 5.1

  5. Recursive Thinking • Reduces a complex problem • into one or more simpler versions of itself

  6. The Ideas Recursive Algorithm to Process Nested Figures if there is one figure do whatever is required to the figure else do whatever is required to the outer figure process the figures nested inside the outer figure in the same way

  7. Example • Searching for a target in an array • Assumption: sorted • Compare with the middle • Search n/2 elements

  8. The Algorithm to Search an Array if the array is empty return -1 as the search result else if the middle matches the target return the subscript of the middle else if the target is less than the middle recursively search the left part else recursively search the right part

  9. The Recursive Algorithm Design • Base case can be solved • Devise a strategy • A problem  base case • Use the smaller problems to solve a larger problem

  10. Recursive Example-1 Finding the Length of a String if the string is empty (has no characters) the length is 0 else the length is 1 plus the length of the string that excludes the first character

  11. Recursive Code /** Recursive method length @param str The string @return The length of the string */ public static int length(String str) { if (str == null || str.equals("")) return 0; else return 1 + length(str.substring(1)); }

  12. Recursive Example-2 Printing String Characters /** Recursive method printChars post: The argument string is displayed, one character per line @param str The string */ public static void printChars(String str) { if (str == null || str.equals("")) return; else { System.out.println(str.charAt(0)); printChars(str.substring(1)); } }

  13. Recursive Example-3 • Printing in Reverse order /** Recursive method printCharsReverse post: The argument string is displayed in reverse, one character per line @param str The string */ public static void printCharsReverse(String str) { if (str == null || str.equals("")) return; else { printCharsReverse(str.substring(1)); System.out.println(str.charAt(0)); } }

  14. Proof • Proof by induction • Prove true for the base case • Assumed true for n • then it must be true for n+1 • Recursive proof is similar to induction • Verify the base case is solved • Each recursive case makes progress towards the base case • if all smaller problems are solved correctly • then the original problem also is solved correctly

  15. Trace a Recursive Method • unwinding the recursion

  16. Implementation in memory? • A new method is called • Java pushes a new activation frame onto the run-time stack • It contains storage for • method arguments • local variables (if any) • the return address

  17. Run-Time Stack

  18. Activation Frames

  19. Recursive Definitions of Mathematical Formulas Section 5.2

  20. Mathematical Formulas • Examples include: • factorials • powers • greatest common divisors (gcd)

  21. Factorial of n: n! • n! is defined as follows: 0! = 1 n! = n x (n -1)! (n > 0) • The base case: n is equal to 0 • The second is a recursive definition

  22. Algorithm of n! ifn equals 0 n! is 1 else n! = n x (n – 1)! • The last step implemented as return n * factorial(n – 1);

  23. The Code for Factorial of n: n! public static int factorial(int n) { if (n == 0) return 1; else return n * factorial(n – 1); }

  24. Stack Overflow • A recursion will not terminate • It will eventually throw an exception • StackOverflowError

  25. Calculating xn Recursive Algorithm for Calculating xn (n ≥ 0) if n is 0 The result is 1 else The result is x × xn–1 Code: public static double power(double x, int n) { if (n == 0) return 1; else return x * power(x, n – 1); }

  26. Calculating gcd • gcd(n1, n2) • the largest integer that divides both numbers • Examples • The gcd of 20 and 15 is 5 • The gcd of 36 and 24 is 12 • The gcd of 38 and 18 is 2 • The gcd of 17 and 97 is 1

  27. Recursive Algorithm • Given 2 positive integers m and n (m > n) if n is a divisor of m gcd(m, n) = n else gcd (m, n) = gcd (n, m % n)

  28. Recursive Code public static double gcd(int m, int n) { if (m % n == 0) return n; else if (m < n) return gcd(n, m); // Transpose arguments. else return gcd(n, m % n); }

  29. Recursion vs. Iteration • Solving a problem? • Recursive algorithm • Easy to write, code, debug, and read • Repeat different bodies • “If approaching the base case” can determine the loop • More memory • Iteration • Repeat the same body • Loop condition determines the loop • More CPU time

  30. Iterative factorial Method public static int factorialIter(int n) { int result = 1; for (int k = 1; k <= n; k++) result = result * k; return result; }

  31. Efficiency of Recursion • Slow • overhead • But more preferable • Readable • Easy to debug

  32. Example: Fibonacci Numbers • Fibonacci numbers • Uses to model the growth of a rabbit colony fib1 = 1 fib2 = 1 fibn = fibn-1 + fibn-2 • 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

  33. An Exponential Recursive fibonacci Method

  34. Efficiency of Recursion: Exponential fibonacci Inefficient

  35. A More Efficient Method

  36. Wrapper method public static int fibonacciStart(int n) { return fibo(1, 0, n); }

  37. Efficiency of Recursion: O(n) fibonacci Efficient

  38. Efficiency fibonacci • tail recursion /last-line recursion • Simple activation frame

  39. Recursive Array Search Section 5.3

  40. Linear Search • Searching an array • can be done by using recursion • Simplest way  a linear search • Examine element one by one • O(n)

  41. Recursive Array Search Idea • Base cases for recursive search: • Empty array  not found • First element == target found • The recursive step searches • the rest of the array

  42. Recursive Linear Array Search Algorithm Algorithm for Recursive Linear Array Search if the array is empty the result is –1 else if the first element matches the target the result is the subscript of the first element else search the array excluding the first element and return the result

  43. Code

  44. Wrapper method public static int linearSearch(Object[] items, Object target) { return linearSearch(items, target, 0); }

  45. demonstration

  46. Binary Search • Sorted array • Base cases • The array is empty • Element being examined matches the target • Check the middle • Then left or right part

  47. Binary Search Algorithm Binary Search Algorithm if the array is empty return –1 as the search result else if the middle element matches the target return the subscript of the middle element as the result else if the target is less than the middle element recursively search the array elements before the middle element and return the result else recursively search the array elements after the middle element and return the result

  48. Example: round 1 target First call Dustin Caryn Debbie Dustin Elliot Jacquie Jonathon Rich first = 0 last = 6 middle = 3

  49. Example: round 2 target Second call Dustin Caryn Debbie Dustin Elliot Jacquie Jonathon Rich first = 0 last = 2 middle = 1

  50. Example: round 3 target Third call Dustin Caryn Debbie Dustin Elliot Jacquie Jonathon Rich first= middle = last = 2

More Related