Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

Similar documents
Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems. COMP Week 8 & 9 1

Recursive Definitions

Recursion -- Introduction

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Recursion Introduction OBJECTIVES

Lecture 24 Tao Wang 1

Sorting & Searching (and a Tower)

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

APCS-AB: Java. Recursion in Java December 12, week14 1

Recursion. Chapter 7

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Recursion. Chapter 5

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

6/4/12. Recursive void Methods. Chapter 11. Vertical Numbers. Vertical Numbers. Vertical Numbers. Algorithm for Vertical Numbers

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

Divide & Conquer. 2. Conquer the sub-problems by solving them recursively. 1. Divide the problem into number of sub-problems

Chapter 13 Recursion. Chapter Objectives

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

Chapter 5: Enhancing Classes

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

Comp 249 Programming Methodology Chapter 11 Recursion

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ).

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003

Module 10. Recursion. Adapted from Absolute Java, Rose Williams, Binghamton University

CmpSci 187: Programming with Data Structures Spring 2015

Reduction & Recursion Overview

Recursive Sequences. Lecture 24 Section 5.6. Robb T. Koether. Hampden-Sydney College. Wed, Feb 27, 2013

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank

Recursive Sequences. Lecture 24 Section 5.6. Robb T. Koether. Hampden-Sydney College. Wed, Feb 26, 2014

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

<The von Koch Snowflake Investigation> properties of fractals is self-similarity. It means that we can magnify them many times and after every

CMSC 150 LECTURE 7 RECURSION

Recursion Chapter 3.5

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Chapter 15: Recursion

CSC 273 Data Structures

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Recursion. What is in This Chapter? Chapter 7

C22a: Problem Solving using Recursion

Boca Raton Community High School AP Computer Science A - Syllabus 2009/10

&KDSWHU$UUD\VDQG9HFWRUV

UNIT 5A Recursion: Basics. Recursion

B. Knowledge of basic algebra and experience in problem solving is beneficial. Students should also possess competence in written communication.

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.


CS 6402 DESIGN AND ANALYSIS OF ALGORITHMS QUESTION BANK

1.7 Recursion. Department of CSE

Plan of the lecture. Quick-Sort. Partition of lists (or using extra workspace) Quick-Sort ( 10.2) Quick-Sort Tree. Partitioning arrays

Fundamentals of Programming Session 13

STUDENT LESSON A9 Recursion

Recursion. Chapter 11

Unit 5: Recursive Thinking

CS200: Recursion and induction (recap from cs161)

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Induction and Recursion. CMPS/MATH 2170: Discrete Mathematics

AP Computer Science AB

Chapter 12 Recursion. Java Software Solutions. Foundations of Program Design Seventh Edition. John Lewis William Loftus

= otherwise W-4 W-1. Overview. CSE 142 Computer Programming I. Overview. Factorial Function

Programming II (CS300)

MEIN 50010: Python Recursive Functions

CS/CE 2336 Computer Science II

Chapter 6 Recursion. The Concept of Recursion

Recursion. notes Chapter 8

12/30/2013 S. NALINI,AP/CSE

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Solving Recursive Sequences by Iteration

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 5. The Towers of Hanoi. Divide and Conquer

Programming II (CS300)

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Bloss, Adrienne and N. Jane Ingram. Lab Manual to Accompany Java Software Solutions. New York, New York: Pearson Education, Inc, 2003.

Programming II (CS300)

Algorithm. Building blocks of algorithm

Chapter 17 - Notes Recursion

mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

Counting Problems; and Recursion! CSCI 2824, Fall 2012!

We cover recursion in 150. Why do it again in 151?

Computer Science and Software Engineering University of Wisconsin - Platteville. 3. Search (Part 1) CS 3030 Lecture Notes Yan Shi UW-Platteville

CSE11 Lecture 20 Fall 2013 Recursion

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING:

csci 210: Data Structures Recursion

Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Instructor: X. Zhang

Recursion. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

Divide and Conquer CISC4080, Computer Algorithms CIS, Fordham Univ. Acknowledgement. Outline

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Koch-Like Fractal Images

Transcription:

Chapter 8: Recursion Presentation slides for Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking A recursive definition is one which uses the word or concept being defined in the definition itself; when defining an English word, a recursive definition usually is not helpful Java Software Solutions is published by Addison-Wesley Presentation slides are copyright 2006 by John Lewis, William Loftus, and Cara Cocking. All rights reserved. Instructors using the textbook may use and modify these slides for pedagogical purposes. *AP is a registered trademark of The College Entrance Examination Board which was not involved in the production of, and does not endorse, this product. But in other 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 3 Recursion Recursive Definitions Recursion is a fundamental programming technique that can provide elegant solutions certain kinds of problems Consider the following list of numbers: 24, 88, 40, 37 Chapter 8 focuses on: thinking in a recursive manner programming in a recursive manner the correct use of recursion examples using recursion recursion in sorting recursion in graphics A list can be defined recursively A LIST is a: number or a: number comma LIST That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself 2 4

Recursive Definitions The recursive part of the LIST definition is used several times, ultimately terminating with the nonrecursive part: number comma LIST 24, 88, 40, 37 number comma LIST 88, 40, 37 number comma LIST 40, 37 Recursive Definitions Mathematical formulas often are 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 as: 1! = 1 N! = N * (N-1)! number 37 5 The concept of the factorial is defined in terms of another factorial until the base case of 1! is reached 7 Infinite Recursion Recursive Definitions All recursive definitions must have a non-recursive part 120 If they don't, there is no way to terminate the recursive path 5! 5 * 4! 24 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 loop 4 * 3! 3 * 2! 2 * 1! 1 6 2 The non-recursive part often is called the base case 6 8

Recursive Programming Recursive Programming A method in Java can invoke itself; if set up that way, it is called a recursive method The code of a recursive method must be structured to handle both the base case and the recursive case Each call to the method sets up a new execution environment, with new parameters and new local variables As always, when the method execution completes, control returns to the method that invoked it (which may be an earlier invocation of itself) public int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum (num - 1); return result; } 9 11 Recursive Programming Recursive Programming Consider the problem of computing the sum of all the numbers between 1 and any positive integer N, inclusive main sum(3) result = 6 This problem can be expressed recursively as: sum result = 3 N i = 1 N-1 = N + = N + (N-1) + i = 1 N-2 i = 1 sum(2) sum result = 1 sum(1) = etc. sum 10 12

Recursion vs. Iteration Indirect Recursion Just because we can use recursion to solve a problem, doesn't mean we should A method invoking itself is considered to be direct recursion For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand; in fact, there is a formula which is superior to both recursion and iteration! You must be able to determine when recursion is the correct technique to use 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 in turn invokes m1 again until a base case is reached This is called indirect recursion, and requires all the same care as direct recursion 13 It is often more difficult to trace and debug 15 Recursion vs. Iteration Indirect Recursion Every recursive solution has a corresponding iterative solution m1 m2 m3 For example, the sum (or the product) of the numbers between 1 and any positive integer N can be calculated with a for loop m1 m2 m3 Recursion has the overhead of multiple method invocations m1 m2 m3 Nevertheless, recursive solutions often are more simple and elegant than iterative solutions 14 16

Maze Traversal Towers of Hanoi We can use recursion to find a path through a maze; a path can be found from any location if a path can be found from any of the location s neighboring locations At each location we encounter, we mark the location as visited and we attempt to find a path from that location s unvisited neighbors Recursion keeps track of the path through the maze The base cases are an prohibited move or arrival at the final destination The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller disks on top The goal is to move all of the disks from one peg to another according to the following rules: We can move only one disk at a time We cannot place a larger disk on top of a smaller disk All disks must be on some peg except for the disk in transit between pegs 17 19 Maze Traversal Towers of Hanoi See MazeSearch.java (page 473) See Maze.java (page 474) A solution to the three-disk Towers of Hanoi puzzle See Figures 8.5 and 8.6 18 20

Towers of Hanoi Recursion in Sorting To move a stack of N disks from the original peg to the destination peg Some sorting algorithms can be implemented recursively move the topmost N - 1 disks from the original peg to the extra peg move the largest disk from the original peg to the destination peg move the N-1 disks from the extra peg to the destination peg The base case occurs when a stack consists of only one disk We will examine two: Merge sort Quick sort This recursive solution is simple and elegant even though the number of move increases exponentially as the number of disks increases The iterative solution to the Towers of Hanoi is much more complex 21 23 Towers of Hanoi Merge Sort See SolveTowers.java (page 479) See TowersOfHanoi.java (page 480) Merge sort divides a list in half, recursively sorts each half, and then combines the two lists At the deepest level of recursion, one-element lists are reached A one-element list is already sorted The work of the sort comes in when the sorted sublists are merge together Merge sort has efficiency O(n log n) See RecursiveSorts.java (page 483) 22 24

Quick Sort Fractals Quick sort partitions a list into two sublists and recursively sorts each sublist Partitioning is done by selecting a pivot value Every element less than the pivot is moved to the left of it Every element greater than the pivot is moved to the right of it The work of the sort is in the partitioning Quick sort has efficiency O(n log n) See RecursiveSorts.java (page 483) 25 A fractal is a geometric shape than can consist of the same pattern repeated in different scales and orientations The Koch Snowflake is a particular fractal that begins with an equilateral triangle To get a higher order of the fractal, the middle of each edge is replaced with two angled line segments 27 Recursion in Graphics Consider the task of repeatedly displaying a set of tiled images in a mosaic in which one of the tiles contains a copy of the entire collage The base case is reached when the area for the remaining tile shrinks to a certain size See TiledPictures.java (page 490) Fractals See Figure 8.9 See KochSnowflake.java (page 493) See KochPanel.java (page 496) 26 28

Summary Chapter 8 has focused on: thinking in a recursive manner programming in a recursive manner the correct use of recursion examples using recursion recursion in sorting recursion in graphics 29