Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.

Similar presentations


Presentation on theme: "1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its."— Presentation transcript:

1 1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its an important programming tool. Readings: Data Structures: A Pseudocode Approach with C++, Chapter 6 Homework: pp. 300-301, Ex. 1-5. Due next Tuesday Programming assignment: Write a non- recursive function for Fibonacci numbers. Due for your portfolio.

2 2 Recursive definitions in mathematics Factorial: 0! = 1base case n! = n * (n-1)! for n > 0recursive case Thus, 3! = 3 * 2! = 3 * 2 * 1! = 3 * 2 * 1 * 0! = 3 * 2 * 1 * 1 (= 6) Fibonacci sequence: Fib 0 = 0 base case Fib 1 = 1 base case Fib n = Fib n-1 + Fib n-2 for n > 1 recursive case 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

3 3 Turn recursive definition into recursive function Factorial: 0! = 1base case n! = n * (n-1)! for n > 0recursive case Thus, 3! = 3 * 2! = 3 * 2 * 1! = 3 * 2 * 1 * 0! = 3 * 2 * 1 * 1 (= 6) // n! (for n>=0) int fact(int n) { if (n == 0) { return 1; base case } else // the case when n is greater than 0 // no need to check return n * fact(n-1); recursive case }(a recursive call) note the precise specification

4 4 Turn recursive definition into recursive function Fibonacci sequence: Fib 0 = 0 base case Fib 1 = 1 base case Fib n = Fib n-1 + Fib n-2 for n > 1 recursive case 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … // Fibonacci number n (for n >= 0) int Fib(int n) { if (n <= 1) { can handle both return n; base cases together } else // the case when n is greater than 0 return Fib(n-1) + Fib(n-2); recursive case } (two recursive calls) note the precise specification

5 5 Two issues with understanding recursion 1. How are recursive calls executed? 2. How do we understand a recursive method and how do we write/create a recursive method? We will handle both issues carefully. But for proper use of recursion they must be kept separate. We DON’T try to understand a recursive method by executing its recursive calls!

6 6 Understanding a recursive method Step 1: Check correctness of the base case. Step 2: Check that recursive-call arguments make progress towards termination. That is, they are in some way smaller than the parameters, so that they approach the base case. Step 3: Check correctness of the recursive case.

7 7 Understanding a recursive method Factorial: !0 = 1base case !n = n * !(n-1) for n > 0recursive case Step 1: Check correctness of the base case. // Fibonacci number n (for n >= 0) int Fib(int n) { if (n <= 1) { can handle both return n; base cases together } else // the case when n is greater than 0 return Fib(n-1) + Fib(n-2); recursive case } (two recursive calls) Here, when n = 0, 1 is returned. Since 0!=1, the base case is handled correctly.

8 8 Understanding a recursive method Factorial: !0 = 1base case !n = n * !(n-1) for n > 0recursive case Step 2: Recursive calls make progress toward termination. // Fibonacci number n (for n >= 0) int Fib(int n) { if (n <= 1) { return n; } else return Fib(n-1) + Fib(n-2); recursive case } argument n-1 is smaller than parameter n, so there is progress toward reaching the base case 0 parameter n argument n-1 argument n-2

9 9 Understanding a recursive method Factorial: !0 = 1base case !n = n * !(n-1) for n > 0recursive case Step 3: Check correctness of the recursive case int fact(int n) { if (n == 0) { return 1; base case } else return n * fact(n-1); recursive case } In the recursive case, the value returned is n * fact(n -1). Using the specification for method fact, we see this is equivalent to n * (n - 1)!. That’s the definition of n!, so the recursive case is correct.

10 10 Creating recursive methods Use the same steps that were involved in understanding a recursive method. Be sure you SPECIFY THE METHOD PRECISELY. Handle the base case first In dealing with the non-base cases, think about how you can express the task in terms of a similar but smaller tasks.

11 11 Stack Usage Consider the function What is going behind the scene? #include using namespace std; int f(int n) { int k, r ; if (n == 0) return 0; // 0 k = n*n; // 1 r = // 2 f(n - 1); // 3 return k + r ; // 4 }

12 12 Stack Usage #include using namespace std; int f(int n) { int k, r; if (n == 0) return 0; // 0 k = n*n; // 1 r = // 2 f(n - 1); // 3 return k + r; // 4 }

13 13 Stack Usage Recursive calls to f get pushed onto stack Multiple copies of function f, each with different arguments & local variable values, and at different lines in function All computer really needs to remember for each active function call is values of arguments & local variables and the location of the next statement to be executed when control goes back The “stack” looks a little more like :

14 14 Recursion vs. Iteration For recursive factorial function: No variable, but n stack elements are saved Therefore time is O(n) memory is O(n) For iterative factorial function: 1 local variable + 1 counter n steps Therefore time is O(n) memory is O(1) Hence, better to use iterative factorial function

15 15 Factorial – non-recursive function Factorial: 0! = 1base case n! = n * (n-1)! for n > 0recursive case Thus, 3! = 3 * 2! = 3 * 2 * 1! = 3 * 2 * 1 * 0! = 3 * 2 * 1 * 1 Therefore 3! = 1*2*3 n! = 1*2*…*n // n! (for n>=0) int fact(int n) { int f=1; for (int i=1; i<=n; i=i+1) f = f* i; return f; } Usually, when transforming a recursive function to an iterative function, the if-statement is replaced by a loop.

16 16 Hanoi Towers The objective of the puzzle is to move the entire stack to another peg, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg. No disk may be placed on top of a smaller disk. The original problem predicted that if there were 100 such disks, the world would come to an end before all the disks could be moved.

17 17 Hanoi Towers A key to solving this puzzle is to recognize that it can be solved by breaking down the problem into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached. For example: label the pegs BEG, AUX, END— these labels may move at different steps let n be the total number of disks number the disks from 1 (smallest, topmost) to n (largest, bottommost) To move n disks from peg BEG to peg END: move n−1 disks from BEG to AUX. This leaves disk n alone on peg BEG move disk n from BEG to END move n−1 disks from AUX to END so they sit on disk n

18 18 Hanoi Towers To move n disks from peg BEG to peg END: move n−1 disks from BEG to AUX. This leaves disk n alone on peg BEG move disk n from BEG to END move n−1 disks from AUX to END so they sit on disk n See animation http://en.wikipedia.org/wiki/File:Tower_of_Hanoi_4.gif http://en.wikipedia.org/wiki/File:Tower_of_Hanoi_4.gif

19 19 Hanoi Towers To move n disks from peg BEG to peg END: move n−1 disks from BEG to AUX. This leaves disk n alone on peg BEG move disk n from BEG to END move n−1 disks from AUX to END so they sit on disk n void Tower (int BEG, int AUX, int END) { if (n>1) { //Move n-1 disks from peg BEG to peg AUX Tower (n-1, BEG, END, AUX) Write (“Move disk n from” BEG “to” END) //Move n-1 disks from peg AUX to peg END Tower (n-1, AUX, BEG, END) }

20 20 Hanoi Towers End of the World? For each n we have two recursive calls. Therefore, this is a tree with the shape: If we assume that all nodes are available, for n disks there will be 2^(n+1) calls. For 100 disks => 2^101 = [2^10 == 1000] = 1000^10 = 1 000 000 000 000 000 000 000 000 000 000 If a disk is moved for a second, this will take 1 000 000 000 000 000 000 000 000 000 000 sec = 31 709 791 983 764 590 000 000 years


Download ppt "1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its."

Similar presentations


Ads by Google