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

Slides:



Advertisements
Similar presentations
Factorial Recursion stack Binary Search Towers of Hanoi
Advertisements

Recursion. Binary search example postponed to end of lecture.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CSC 212 Recursion By Dr. Waleed Alsalih. Definition A recursive function (method) is one that calls itself. A recursive method must have a basis part.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Chapter 14: Recursion Starting Out with C++ Early Objects
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Recursion. Functions – reminder A function can call other functions. Return causes the execution of the function to terminate and returns a value to the.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Recursion. Circular Definition Circular definition Circular definition Dialectic materialism is materialism that is dialectic. Dialectic materialism is.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Lecture - 8 On Stacks, Recursion. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline Quick sort Algorithm Recursion –Calculate n factorial –Fibonacci.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
CMPF144 FUNDAMENTALS OF COMPUTING THEORY Module 9: The Tower of Hanoi.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
1 Recursion and induction We teach these early, instead of new object- oriented ideas, so that those who are new to Java can have a chance to catch up.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Recursion.
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
Chapter 15 Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Chapter 11.
CS1120: Recursion.
Chapter 8: Recursion Java Software Solutions
Recursion Data Structures.
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Module 1-10: Recursion.
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

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 , Ex Due next Tuesday Programming assignment: Write a non- recursive function for Fibonacci numbers. Due for your portfolio.

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

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 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 = If a disk is moved for a second, this will take sec = years