CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.

Slides:



Advertisements
Similar presentations
© 2006 Pearson Education Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William.
Advertisements

Chapter 17 Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter 8: Recursion Java Software Solutions
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Recursion Chapter 8. 2 Chapter Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an.
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
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.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
Recursion Chapter 5.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
M180: Data Structures & Algorithms in Java
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
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.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
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.
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.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
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 Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Recursion Chapter 10 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 6 Corrected Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points.
Recursion.
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
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
Recursion Chapter 10.
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 (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Chapter 8: Recursion Java Software Solutions
Recursion (part 1) October 24, 2007 ComS 207: Programming I (in Java)
Unit 3 Test: Friday.
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Java Software Solutions Foundations of Program Design Sixth Edition
Recursive Thinking.
Recursion (part 1) October 25, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat

Recursive Definitions  Consider the following list of numbers: 24, 88, 40, 37  Such a list can be defined recursively: A LIST is a:number or a:number comma LIST  That is, a LIST can be a number, or a number followed by a comma followed by a LIST  The concept of a LIST is used to define itself 2

Tracing the recursive definition of a list LIST:numbercommaLIST 24,88, 40, 37 numbercommaLIST 88,40, 37 numbercommaLIST 40, 37 number 37 3

What Is Recursion?  It is a problem-solving process  Breaks a problem into identical but smaller problems  Eventually you reach a smallest problem  Answer is obvious or trivial  Using that solution enables you to solve the previous problems  Eventually the original problem is solved 4

Recursive Thinking  Recursion is a programming technique in which a method can call itself in order to fulfill its purpose  A recursive definition is one which uses the word or concept being defined in the definition itself  In some situations, a recursive definition can be an appropriate way to express a concept  Before applying recursion to programming, it is best to practice thinking recursively 5

Infinite Recursion  All recursive definitions must have a non-recursive part  If they don't, there is no way to terminate the recursive path  A definition without a non-recursive part causes infinite recursion  This problem is similar to an infinite loop -- with the definition itself causing the infinite “looping”  The non-recursive part often is called the base case 6

Parts of a Recursive Definition Every recursive definition contains two parts:  a base case, which is non-recursive and, consequently, terminates the recursive application of the rule.  a recursive case, which reapplies a rule. 7

Direct vs. Indirect Recursion  A method invoking itself is considered to be direct recursion  A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again  For example, method m1 could invoke m2, which invokes m3, which invokes m1 again  This is called indirect recursion  It is often more difficult to trace and debug 8

Direct vs. Indirect Recursion m1m2m3 m1m2m3 m1m2m3 9

Phases of Recursion Forward Phase: Every recursion has a forward phase in which a call at every level, except the last, spins off a call to the next level, and waits for the latter call to return control it.  Backward Phase: Every recursion has a backtracking phase in which a call at every level, except the first, passes control back to the previous level, at which point the call waiting at the previous level wakes up and resumes its work. 10

Examples: Simple problems  Summation  Factorial  Fibonacci 11

Summation 12

The sum of 1 to N, defined recursively int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum(num-1); return result; } Base case Recursive case 13

Recursive calls to the sum method main sum result = 4 + sum(3) sum(4) sum(3) sum(2) sum(1) result = 1 result = 3 + sum(2) result = 2 + sum(1) 14

Factorial  Mathematical formulas are often expressed recursively  N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive  This definition can be expressed recursively: 1! = 1 N! = N * (N-1)!  A factorial is defined in terms of another factorial until the base case of 1! is reached 15

Factorial Function  N is 1 x 2 x 3 x... x N – 1 x N 16

Computing the Factorial  A recursive program implements a recursive definition.  The main work in writing a recursive method to solve a specific problem is to define base cases. 17

Computing the Factorial (Cont.) 18

Fibonacci Sequence fib n – 1 + fib n – 2, if n > 1 recursive case fib n = 0, if n == 0 base case 1, if n == 1 base case 19

Fibonacci Sequence  Definition of F(4) spins off two chains of recursion, one on F(3) and another on F(2).  Every chain either ends in F(0) or F(1) 20

Computing the Fibonacci Sequence 21

Computing the Fibonacci Sequence (Cont.)  Every call waits on two subsequent calls.  These waits are not simultaneous.  For every call there is a wait-wakeup-wait-wakeup cycle. Except the F(0) and F(1). There are two forward phases and two backtracking phases. 22

Avoiding Recursion 23 int fibo(int n) { if (n < 2) return 1; else return fibo(n-1) + fibo(n-2); }

Avoiding Recursion 24

Avoiding Recursion 25 int fibo(int n) { int f[n]; f[0]=0; f[1]=1; for (int i=2; i<=n; i++) f[i] = f[i-1] + f[i-2]; return f[n]; }

A Simple Solution to a Difficult Problem  The Towers of Hanoi 26

Towers of Hanoi: An Application  There are three towers or pegs, A, B, and C, and a pile of disks of various sizes. The disks start on peg A. Move all the disks from peg A to C, using B as an intermediate. (a) only one disk can be moved at a time. (b) a larger disk can never go on top of a smaller one. 27

Towers of Hanoi: Base cases  The smallest instance of the problem is when there is only one disk in the stack.  Simply move the disk from peg A to C.  With 2 disks:  Top disk moves to B  Bottom disk moves to C.  Top disk moves from B to C. 28

Towers of Hanoi: Recursive cases  With three disks: We move two disks out of the way from A to B. We move the bottom disk from A to C. We move the two disks from B to C.  We are not allowed to move two disks at a time.  Sub-problems requires us to move two disks from one beg to another, which we already know how to do. 29

Towers of Hanoi: Recursive cases(Cont.)  Two-disk problem moved two disks from A to C.  Three-disk problem, the first two-disk sub-problem moves disks from A to B.  Second two-disk sub-problem moves disks form B to C.  Providing the source destination, and intermediate pegs can generalize the sub-problem. 30

Towers of Hanoi: All together  Recursive definition of towers of Hanoi solution for any n.  Solve the towers of Hanoi problem for n – 1, with source peg A, destination peg B, intermediate peg C.  Move a disk from A to C.  Solve the towers of Hanoi problem for n – 1, with source peg B, destination peg C, intermediate peg A. 31

Towers of Hanoi: An example The sequence of moves for solving the Towers of Hanoi problem with three disks. Continued → 32

Towers of Hanoi: An example (Cont.) (Continued) The sequence of moves for solving the Towers of Hanoi problem with three disks. 33

Towers of Hanoi: An example (Cont.) (Continued) The smaller problems in a recursive solution for four disks 34

Towers of Hanoi: The algorithm Algorithm to solve Towers of Hanoi Puzzle Algorithm solveTowers (numberOfDisks, startPole, tempPole, endPole) if (numberOfDisks == 1) Move disk from startPole to endPole else { solveTowers (numberOfDisks - 1, startPole, endPole, tempPole) Move disk from startPole to endPole solveTowers (numberOfDisks - 1, tempPole, startPole, endPole) } 35

Recursion vs. Iteration  Comparison of elements of a loop and a recursive function LoopRecursive Method loop control variablemethod input loop exit conditionbase case loop entry conditionrecursive case loop bodymethod body 36

Recursion vs. Iteration  Just because we can use recursion to solve a problem, doesn't mean we should  For instance, we usually would not use recursion to solve the sum of 1 to N  The iterative version is easier to understand (in fact there is a formula that is superior to both recursion and iteration in this case)  You must be able to determine when recursion is the correct technique to use 37

Recursion vs. Iteration  Every recursive solution has a corresponding iterative solution  For example, the sum of the numbers between 1 and N can be calculated with a loop  Recursion has the overhead of multiple method invocations  However, for some problems recursive solutions are often more simple and elegant than iterative solutions 38

Drawbacks of Recursion  Stack space that is used to implement it.  Every recursive method call produces a new instance of the method, with a new set of local variables (including parameters).  Computing the factorial of a number. Local information pertaining to each of the calls to fact(N), fact(N-1), etc. all the way down to fact(2) is stored on stack. fact (N) would consume O(N) worth of stack space. 39

Drawbacks of Recursion (Cont.)  Certain computations may be performed redundantly.  The Fibonacci sequence. In computing F(4), F(2) is computed twice. F(5)? F(3) is computed twice, which involves a computation of F(2), and there is another computation of F(2) by itself. Things thus get worse as we recursively compute the Fibonacci sequence for bigger and bigger numbers. Not to mention the stack space used. 40

Drawbacks of Recursion (Cont.)  One has to weigh the simplicity of code delivered by recursion against its drawbacks.  When iterative solution is obvious.  There are several problems for which such iterative solutions are not obviously forthcoming. 41

Summary  Defining the base case is vital.  Building on the base case(s) to solve a problem results in defining the recursive case.  It is not always right to use recursive solutions. Applying recursive on simple problems may result in inefficiency in terms of time and redundancy (Fibonacci).  Recursion is simple, efficient, and elegant solution if applied to the right problem (Towers of Hanoi). 42