COSC 2006 Data Structures I Recursion I

Post on 01-Jan-2016

33 views 6 download

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

transcript

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

Recursion is easy to understand (trust me!) The only thing mysterious about recursion

is why so many students find it frightening!

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

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

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

Recursive Examples

Some everyday situations can be described recursively

Examples: Searching in dictionaries

Exercise: What other real-life situations do you believe

are recursive?

Example: Searching Dictionary

Steps when searching in a dictionary

Option1: Sequential searchLengthy & inefficient if the dictionary had

many pages

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

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?

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}

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

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

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

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

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

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

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

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

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?

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.

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.

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;

}

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

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

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

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