34
COSC 2006 Data Structures I Recursion I

COSC 2006 Data Structures I Recursion I

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: COSC 2006 Data Structures I Recursion I

COSC 2006 Data Structures IRecursion I

Page 2: COSC 2006 Data Structures I Recursion I

Topics

Recursion vs. Iteration

Characteristics of Recursion

Recursive Examples

Constructing & Tracing Recursive

Solutions

Page 3: COSC 2006 Data Structures I Recursion I

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!

Page 4: COSC 2006 Data Structures I Recursion I

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

Page 5: COSC 2006 Data Structures I Recursion I

04/20/23

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!)

Page 6: COSC 2006 Data Structures I Recursion I

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

Page 7: COSC 2006 Data Structures I Recursion I

Recursive Examples

Some everyday situations can be described recursively

Examples: Searching in dictionaries

Exercise: What other real-life situations do you believe

are recursive?

Page 8: COSC 2006 Data Structures I Recursion I

Example: Searching Dictionary

Steps when searching in a dictionary

Option1: Sequential searchLengthy & inefficient if the dictionary had

many pages

Page 9: COSC 2006 Data Structures I Recursion I

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

Page 10: COSC 2006 Data Structures I Recursion I

04/20/23

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?

Page 11: COSC 2006 Data Structures I Recursion I

Example: Searching Dictionary

Algorithm: First Draft

// Search a dictionary for a word by using// recursive binary searchif (Dictionary contains 1 page)

scan the page for the wordelse{ Open a page near the middle

Determine which half contains the wordif (word in first half)

search first half for the wordelse

search second half for the word}

Page 12: COSC 2006 Data Structures I Recursion I

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

Search Dictionary

Search Second Halfof Dictionary

Search First Half of Dictionary

OR

Page 13: COSC 2006 Data Structures I Recursion I

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 casescan 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

Page 14: COSC 2006 Data Structures I Recursion I

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

Page 15: COSC 2006 Data Structures I Recursion I

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

Page 16: COSC 2006 Data Structures I Recursion I

04/20/23

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 factorialfactorial (n)

1, if n 0

n * factorial(n 1), if n 0

Page 17: COSC 2006 Data Structures I Recursion I

04/20/23

Example: Factorial (cont)

public static int fact(int n) {if (n == 0) {

return 1;else {

return n * fact(n-1); }

}

factorial (n) 1, if n 0

n * factorial(n 1), if n 0

Page 18: COSC 2006 Data Structures I Recursion I

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

Page 19: COSC 2006 Data Structures I Recursion I

04/20/23

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));

Page 20: COSC 2006 Data Structures I Recursion I

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?

Page 21: COSC 2006 Data Structures I Recursion I

Stack Frames

System Stack used to control which function is currently active and to reverse the order of function calls when returning.

Stack Framea variable size piece of memory that is pushed onto the system stack each time a function call is made.

Page 22: COSC 2006 Data Structures I Recursion I

Stack Frames

Stack Frame contains:space for all local (automatic) variablesthe return address - the place in the program to which execution will return when this function endsthe return value from the functionall 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.

Page 23: COSC 2006 Data Structures I Recursion I

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;

}

Page 24: COSC 2006 Data Structures I Recursion I

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

Page 25: COSC 2006 Data Structures I Recursion I

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 = 1all other Fibonacci numbers are defined as the sum of the previous two

Page 26: COSC 2006 Data Structures I Recursion I

Fibonacci Numbers (skip the rabbits)

1 if n is 1 or 2Fib(n) =

Fib(n-1) + Fib(n-2) otherwise{

Public static int fib(int n) {if (n <= 2) {

return 1else {

return fib (n-1) + fib(n-2) }} See textbook for trace … how many times

is fib(3) computed?

Multiple calls and base cases

Page 27: COSC 2006 Data Structures I Recursion I

27

Review In a recursive solution, the ______

terminates the recursive processing. local environment pivot item base case recurrence relation

Page 28: COSC 2006 Data Structures I Recursion I

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

Page 29: COSC 2006 Data Structures I Recursion I

29

Review The factorial of n is equal to ______.

n – 1 n – factorial (n–1) factorial (n–1) n * factorial (n–1)

Page 30: COSC 2006 Data Structures I Recursion I

30

Review The base case for a recursive definition

of the factorial of n is ______. factorial (–1) factorial (0) factorial (1) factorial (n – 1)

Page 31: COSC 2006 Data Structures I Recursion I

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

Page 32: COSC 2006 Data Structures I Recursion I

32

Review In the box trace, each box roughly

corresponds to a(n) ______. recursive relation activation record base case pivot item

Page 33: COSC 2006 Data Structures I Recursion I

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

Page 34: COSC 2006 Data Structures I Recursion I

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