1 / 34

COSC 2006 Data Structures I Recursion I

COSC 2006 Data Structures I Recursion I. Topics. Recursion vs. Iteration Characteristics of Recursion Recursive Examples Constructing & Tracing Recursive Solutions. Introduction. Recursion makes complex problems easier by breaking them down into simpler versions of the same problem

baxter-day
Download Presentation

COSC 2006 Data Structures I Recursion I

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. COSC 2006 Data Structures IRecursion I

  2. Topics • Recursion vs. Iteration • Characteristics of Recursion • Recursive Examples • Constructing & Tracing Recursive Solutions

  3. Introduction • Recursion makes complex problems easier by breaking them down into simpler versions of the same problem • Recursion is easy to understand (trust me!) • The only thing mysterious about recursion is why so many students find it frightening!

  4. Introduction Recursion • Math definition: • a solution to a problem that is defined in terms of a simpler version of itself • Programming definition: • a function which calls itself

  5. Gist • Take a problem and break it down into identical, but smaller, problems • Do it in such a manner that eventually the smaller problems become trivial to solve. These are the base cases. • Once you have analyzed your problem in this way, you can write a method that • Checks for and solves the base case (easy!) • Otherwise calls itself on smaller problems (easy!)

  6. Recursive Examples • Some concepts are naturally defined recursively • Examples: • Multiplication: • a b = a (b - 1 ) + a base case = a = a + a + . . . + a b-times • Exponentiation: • ab = a( b-1) a base case = a = a a a . . . a b-times

  7. Recursive Examples • Some everyday situations can be described recursively • Examples: • Searching in dictionaries • Exercise: • What other real-life situations do you believe are recursive?

  8. Example: Searching Dictionary • Steps when searching in a dictionary • Option1: Sequential search • Lengthy & inefficient if the dictionary had many pages

  9. Example: Dictionary Option 2: • Open to a page (somewhere in the middle): this divides the problem into smaller problems • Is it on the page you opened to? Retrieve the definition (base case #1) • Is this the only page in the dictionary? Return failure: it is not in the dictionary (base case #2) • If not, determine which half it is in and recurse on that half as if it were the whole dictionary

  10. Four Questions • How can you define the problem in terms of a smaller problem of the same type? • How does each recursive call diminish the size of the problem? • What instance of the problem can serve as the base case? • As the problem size diminishes, will you reach this base case?

  11. Example: Searching Dictionary • Algorithm: First Draft // Search a dictionary for a word by using // recursive binary search if (Dictionary contains 1 page) scan the page for the word else { Open a page near the middle Determine which half contains the word if (word in first half) search first half for the word else search second half for the word }

  12. Search Dictionary OR Search First Half of Dictionary Search Second Half of Dictionary Example: Searching Dictionary • Observations on first draft: • The problem of searching for a word is reduced by half each time • Once we divide the dictionary into two halves, we use the same strategy to search the appropriate half • Special case (base / degenerate / termination): • Different from all other cases (single page) • Does not contain recursive call

  13. Example: Searching Dictionary • Algorithm: Second Draft search (in aDictionary: Dictionary,in Word: string) // Search a dictionary for a word by using // recursive search { if (aDictionary contains 1 page) // Base case scan the page for the word else { Open aDictionary to point to a page near the middle Determine which half contains the word if (word in first half of aDictionary) search (first half of aDictionary, word) else search (second half of aDictionary, word) } // end if } // end search

  14. Example: Searching Dictionary • Observations • The recursive one is more efficient than the iterative solution • The Fact function fits the model of recursive solution • It calls itself • At each recursive call the value of page diminishes by half • The base case occurs when it is one page • If there are pages in dictionary, the base case is always reached

  15. Recursive Functions Criteria 1. Function calls itself 2. Each call solves an simpler (smaller in size), but identical problem 3. Base case is handled differently from all other cases and enables recursive calls to stop 4. The size of the problem diminishes and ensures reaching the base case

  16. Example: Factorial • Iterative definition:factorial(n) = n * (n-1) * (n-2) * … * 1 for any integer n > 0factorial(0) = 1 • A recurrence relationfactorial(n) = n * [(n-1) * (n-2) * … * 1]factorial(n) = n * factorial(n-1) • A recursive definition of factorial

  17. Example: Factorial (cont) public static int fact(int n) { if (n == 0) { return 1; else { return n * fact(n-1); } }

  18. Recursion vs. Iteration • Iteration • Involves loops • Needs a termination condition • Based on initial, final, & step values • Solutions could be lengthy & complex • Recursion • Involves recursive calls • Provide some elegant & short solutions for complex problems • Needs a termination condition • Based on divide & conquer

  19. Example: Factorial (cont) public static int fact(int n) {int temp; System.out.println("Entering factorial: n = " + n); if (n == 0) { temp= 1; } else { temp = n * fact(n-1); } System.out.println("Leaving factorial: n = "+ n ); return temp; } Call: System.out.println("Factorial(4):" + factorial(4));

  20. Example: Factorial • Observations • The iterative solution is more efficient than the recursive one • The Fact function fits the model of recursive solution • It calls itself • At each recursive call the value of n diminishes by 1 • The base case occurs when n = 0 • If n is non-negative, the base case is always reached • Any problem with the recursion version?

  21. Stack Frames • System Stack • used to control which function is currently active and to reverse the order of function calls when returning. • Stack Frame • a variable size piece of memory that is pushed onto the system stack each time a function call is made.

  22. Stack Frames • Stack Frame contains: • space for all local (automatic) variables • the return address - the place in the program to which execution will return when this function ends • the return value from the function • all parameters for a function (with actual parameter values copied in • The stack frame on top of the stack always represents the function being executed at any point in time - only the stack frame on top of the stack is accessible at any time.

  23. Stack Frames public class Test { public static void main (String [] args) { double a =1, b=2, c= 3 x= 4; System.out.println(“Line function”+ Line (a,b,x)); System.out.println (“Quadratic function”+Quadratic (a,b,c,x)); } static double Line (double a, double b, double x) { double y = a*x+b; return y; } static double Quadratic (double a, double b, double c, double x) { double y = a*x*x+b*x+c; return y; }

  24. Types of Recursion • Direct recursion: • When a function calls itself • Multiple recursion • Indirect recursion: • When a function calls another function, that eventually calls the original function • Mutual recursion: • When two functions call each other

  25. Multiple Recursion • Fibonacci Sequence: 0 1 1 2 3 5 8 13 21 44 • each number in sequence is the sum of the previous two numbers (except the first two) • Fibonacci number 0 = 0 • Fibonacci number 1 = 1 • all other Fibonacci numbers are defined as the sum of the previous two

  26. Fibonacci Numbers (skip the rabbits) { 1 if n is 1 or 2 Fib(n) = Fib(n-1) + Fib(n-2) otherwise Public static int fib(int n) { if (n <= 2) { return 1 else { return fib (n-1) + fib(n-2) } } Multiple calls and base cases See textbook for trace … how many times is fib(3) computed?

  27. Review • In a recursive solution, the ______ terminates the recursive processing. • local environment • pivot item • base case • recurrence relation

  28. Review • A ______ is a mathematical formula that generates the terms in a sequence from previous terms. • local environment • pivot item • base case • recurrence relation

  29. Review • The factorial of n is equal to ______. • n – 1 • n – factorial (n–1) • factorial (n–1) • n * factorial (n–1)

  30. Review • The base case for a recursive definition of the factorial of n is ______. • factorial (–1) • factorial (0) • factorial (1) • factorial (n – 1)

  31. Review • What would happen if a negative value is passed to a method that returns the factorial of the value passed to it? • the method will calculate the correct value for the factorial of the number • the method will calculate a negative value for the factorial of the number • the method would terminate immediately • an infinite sequence of recursive calls will occur

  32. Review • In the box trace, each box roughly corresponds to a(n) ______. • recursive relation • activation record • base case • pivot item

  33. Review • In the box trace, each box contains all of the following EXCEPT ______. • the values of the references and primitive types of the method’s arguments • the method’s local variables • the method’s class variables • a placeholder for the value returned by each recursive call from the current box

  34. Review • In the box trace for a recursive method, a new box is created each time ______. • the method is called • the method returns a value • the object is created • the object is initialized

More Related