 1992-2007 Pearson Education, Inc. All rights reserved. 1 15 Recursion.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
Recursion. Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn about recursive algorithms Lecture.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
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.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Department of Computer Science Data Structures Using C++ 2E Chapter 6: Recursion Learn about recursive Definitions Algorithms Functions Explore the base.
 2008 Pearson Education, Inc. All rights reserved Function Call Stack and Activation Records Data structure: collection of related data items.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Data Structures and Abstractions with Java, 4e Frank Carrano
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Lecture 12 Recursion part 1 Richard Gesick. Recursion A recursive method is a method that calls itself. A recursive method is capable of solving only.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
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.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
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,
 2005 Pearson Education, Inc. All rights reserved Recursion.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
1 Recursion Recursive method –Calls itself (directly or indirectly) through another method –Method knows how to solve only a base case –Method divides.
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
 Prentice Hall. All rights reserved. 1 CS 1120 – Computer Science II Recursion (Ch.15) Many slides modified by Prof. L. Lilien (even many without.
 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.
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.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
Java How to Program, 10/e Late Objects Version © Copyright by Pearson Education, Inc. All Rights Reserved.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
 2006 Pearson Education, Inc. All rights reserved Functions and an Introduction to Recursion.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
RECURSION.
Chapter 8: Recursion Java Software Solutions
15 Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
MSIS 655 Advanced Business Applications Programming
Recursion (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Lecture 17 Recursion part 1 Richard Gesick.
Chapter 8: Recursion Java Software Solutions
Functions Recursion CSCI 230
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Lecture 12 Recursion part 1 CSE /26/2018.
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Programming Fundamentals Lecture #7 Functions
Java Software Solutions Foundations of Program Design Sixth Edition
Presentation transcript:

 Pearson Education, Inc. All rights reserved Recursion

 Pearson Education, Inc. All rights reserved. 2 We must learn to explore all the options and possibilities that confront us in a complex and rapidly changing world. — James William Fulbright O! thou hast damnable iteration, and art indeed able to corrupt a saint. — William Shakespeare It's a poor sort of memory that only works backwards. — Lewis Carroll, Alice in Wonderland Life can only be understood backwards; but it must be lived forwards. — Soren Kierkegaard Push on—keep moving. — Thomas Morton

 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn:  The concept of recursion.  How to write and use recursive methods.  How to determine the base case and recursion step in a recursive algorithm.  How recursive method calls are handled by the system.  The differences between recursion and iteration, and when it is appropriate to use each.  What geometric shapes called fractals are and how to draw them using recursion.  What recursive backtracking is and why it is an effective problem-solving technique.

 Pearson Education, Inc. All rights reserved Introduction 15.2 Recursion Concepts 15.3 Example Using Recursion: Factorials 15.4 Example Using Recursion: Fibonacci Series 15.5 Recursion and the Method Call Stack 15.6 Recursion vs. Iteration 15.7 Towers of Hanoi 15.8 Fractals 15.9 Recursive Backtracking Wrap-Up Internet and Web Resources

 Pearson Education, Inc. All rights reserved Introduction Earlier programs structured as methods that call one another in a disciplined, hierarchical manner Recursive methods – Call themselves – Useful for some problems to define a method to call itself – Can be called directly or indirectly through another method

 Pearson Education, Inc. All rights reserved. 6 Fig | Summary of the 32 recursion examples and exercises in this text. (Part 1 of 2)

 Pearson Education, Inc. All rights reserved. 7 Fig | Summary of the 32 recursion examples and exercises in this text. (Part 2 of 2)

 Pearson Education, Inc. All rights reserved Recursion Concepts Recursive problem-solving elements – Base case Recursive method capable of solving only simplest case—the base case If method is called with base case, method returns result – If method is called with more complex problem, problem divided into two pieces—a piece the method knows how to do and a piece the method does not know how to do (called recursive call or recursion step) – Recursive call/recursion step Must resemble original problem but be slightly simpler or smaller version Method calls fresh copy of itself to work on smaller problem Normally includes return statement Indirect recursion – Recursive method calls another method that eventually makes call back to recursive method

 Pearson Education, Inc. All rights reserved Example Using Recursion: Factorials Factorial of n, or n! is the product n · (n – 1) · (n – 2) · … · 1 With 1! equal to 1 and 0! Defined to be 1. Can be solved recursively or iteratively (nonrecursively) Recursive solution uses following relationship: n! = n · (n – 1)! Infinite recursion – recursive calls are continuously made until memory has been exhausted – Caused by either omitting base case or writing recursion step that does not converge on base case

 Pearson Education, Inc. All rights reserved. 10 Fig | Recursive evaluation of 5!.

 Pearson Education, Inc. All rights reserved. 11 Base case returns 1 Portion method knows how to do Recursion step breaks problem into two parts: one the method knows how to do, one the method does not Recursive call: Portion method does not know how to do; smaller version of original problem Original call to recursive method

 Pearson Education, Inc. All rights reserved. 12 Common Programming Error 15.1 Either omitting the base case or writing the recursion step incorrectly so that it does not converge on the base case can cause a logic error known as infinite recursion, where recursive calls are continuously made until memory has been exhausted. This error is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

 Pearson Education, Inc. All rights reserved. 13 Calculate and display factorials

 Pearson Education, Inc. All rights reserved Example Using Recursion: Fibonacci Series Fibonacci series begins with 0 and 1 and has property that each subsequent Fibonacci number is the sum of previous two Fibonacci numbers. Series occurs in nature, ratio of successive Fibonacci numbers converges on golden ratio or golden mean Fibonacci series defined recursively as: fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2) Recursive solution for calculating Fibonacci values results in explosion of recursive method calls

 Pearson Education, Inc. All rights reserved. 15 Two base casesTwo recursive calls Original call to recursive method

 Pearson Education, Inc. All rights reserved. 16 Calculate and display Fibonacci values

 Pearson Education, Inc. All rights reserved. 17 Fig | Set of recursive calls for fibonacci( 3 ).

 Pearson Education, Inc. All rights reserved. 18 Avoid Fibonacci-style recursive programs, because they result in an exponential “explosion” of method calls. Performance Tip 15.1

 Pearson Education, Inc. All rights reserved Recursion and the Method Call Stack Method call stack used to keep track of method calls and local variables within a method call Just as with nonrecursive programming, recursive method calls are placed at the top of the method call stack As recursive method calls return, their activation records are popped off the stack and the previous recursive calls continue executing Current method executing is always method whose activation record is at top of stack

 Pearson Education, Inc. All rights reserved. 20 Fig | Method calls made within the call fibonacci( 3 ).

 Pearson Education, Inc. All rights reserved. 21 Fig | Method calls on the program execution stack.

 Pearson Education, Inc. All rights reserved Recursion vs. Iteration Any problem that can be solved recursively can be solved iteratively Both iteration and recursion use a control statement – Iteration uses a repetition statement – Recursion uses a selection statement Iteration and recursion both involve a termination test – Iteration terminates when the loop-continuation condition fails – Recursion terminates when a base case is reached Recursion can be expensive in terms of processor time and memory space, but usually provides a more intuitive solution

 Pearson Education, Inc. All rights reserved. 23 Iterative solution uses counter-controlled repetition

 Pearson Education, Inc. All rights reserved. 24

 Pearson Education, Inc. All rights reserved. 25 Software Engineering Observation 15.1 Any problem that can be solved recursively can also be solved iteratively (nonrecursively). A recursive approach is normally preferred over an iterative approach when the recursive approach more naturally mirrors the problem and results in a program that is easier to understand and debug. A recursive approach can often be implemented with fewer lines of code. Another reason to choose a recursive approach is that an iterative one might not be apparent.

 Pearson Education, Inc. All rights reserved. 26 Avoid using recursion in situations requiring high performance. Recursive calls take time and consume additional memory. Performance Tip 15.2

 Pearson Education, Inc. All rights reserved. 27 Common Programming Error 15.2 Accidentally having a nonrecursive method call itself either directly or indirectly through another method can cause infinite recursion.

 Pearson Education, Inc. All rights reserved Towers of Hanoi Classic problem – Priests in Far East are attempting to move a stack of disks from one peg to another. One disk must be moved at a time, at no time may a larger disk be placed above a smaller disk Recursive solution: – Move n – 1 disks from peg 1 to peg 2, using peg 3 as temporary holding area – Move the last disk (the largest) from peg 1 to peg 3 – Move the n – 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area Base case: When only one disk needs to be moved – no temporary holding area needed, disk is simply moved

 Pearson Education, Inc. All rights reserved. 29 Fig | Towers of Hanoi for the case with four disks.

 Pearson Education, Inc. All rights reserved. 30 Base case: Simply display move

 Pearson Education, Inc. All rights reserved. 31 Move n-1 disks from peg 1 to peg 2 Move last disk from peg 1 to peg 3 Move n-1 disks from peg 2 to peg 3Use peg 1 as temporary holding area Use peg 3 as temporary holding area

 Pearson Education, Inc. All rights reserved. 32 Make initial call to recursive method

 Pearson Education, Inc. All rights reserved Fractals Fractal – a geometric figure that often can be generated from a pattern repeated recursively an infinite number of times Pattern applied to each segment of original figure Benoit Mandelbrot introduced term “fractal,” along with specifics of how fractals are created and their practical applications – Help us better understand patterns in nature, the human body and the universe – Popular art form

 Pearson Education, Inc. All rights reserved Fractals Self-similar property – fractals have this property in the case that, when subdivided into parts, each resembles a reduced-size copy of the whole If part is exact copy of original, fractal is said to be strictly self similar Each time pattern is applied, fractal is said to be at new level or depth Fractal examples: Koch Curve, Koch Snowflake

 Pearson Education, Inc. All rights reserved. 35 Fig | Koch Curve fractal. (a)(b) (c)(d) (e)(f)

 Pearson Education, Inc. All rights reserved. 36 Fig | “Lo fractal” at level 0.

 Pearson Education, Inc. All rights reserved. 37 Fig | Determining points C and D for level 1 of “Lo fractal.”

 Pearson Education, Inc. All rights reserved. 38 Fig | “Lo fractal” at level 1, with C and D points determined for level 2. [Note: The fractal at level 0 is included as a dashed line as a reminder of where the line was located in relation to the current fractal.]

 Pearson Education, Inc. All rights reserved. 39 Fig | “Lo fractal” at level 2, with dashed lines from level 1 provided.

 Pearson Education, Inc. All rights reserved. 40 Fig | “Lo fractal” at level 2.

 Pearson Education, Inc. All rights reserved. 41

 Pearson Education, Inc. All rights reserved. 42

 Pearson Education, Inc. All rights reserved. 43 Retrieve current levelDecrease levelSet new level Redraw fractal up to new level

 Pearson Education, Inc. All rights reserved. 44 Retrieve current levelIncrease levelSet new level Redraw fractal up to new level

 Pearson Education, Inc. All rights reserved. 45

 Pearson Education, Inc. All rights reserved. 46

 Pearson Education, Inc. All rights reserved. 47 Coordinates of first point for line where fractal is being applied Coordinates of second point for line where fractal is being applied Base case: Simply draw line, pattern is not applied Recursion step: Apply fractal pattern Calculate midpointCalculate point to form right triangle Apply pattern to three new lines

 Pearson Education, Inc. All rights reserved. 48 Make first call to recursive method whenever window is repainted

 Pearson Education, Inc. All rights reserved. 49

 Pearson Education, Inc. All rights reserved. 50

 Pearson Education, Inc. All rights reserved. 51

 Pearson Education, Inc. All rights reserved Recursive Backtracking Recursive Backtracking – process of using recursion to return to earlier decision point If one set of recursive calls does not result in solution, program backs up to previous decision point and makes different decision, often resulting in another set of recursive calls Examples – Maze problem – Eight-Queens problem