Chapter 8: Recursion

Similar documents
Comparison Sorts. EECS 2011 Prof. J. Elder - 1 -

Priority Queues & Heaps

Priority Queues & Heaps

Priority Queues & Heaps

Hoboken Public Schools. Algebra II Honors Curriculum

Midterm Review. EECS 2011 Prof. J. Elder - 1 -

Tie Breaking in STV. 1 Introduction. 3 The special case of ties with the Meek algorithm. 2 Ties in practice

Hoboken Public Schools. AP Calculus Curriculum

Search Trees. Chapter 10. CSE 2011 Prof. J. Elder Last Updated: :51 PM

ECE250: Algorithms and Data Structures Trees

Text UI. Data Store Ø Example of a backend to a real Could add a different user interface. Good judgment comes from experience

Plan For the Week. Solve problems by programming in Python. Compsci 101 Way-of-life. Vocabulary and Concepts

STUDY GUIDE FOR TEST 2

Midterm Review. EECS 2011 Prof. J. Elder - 1 -

Essential Questions Content Skills Assessments Standards/PIs. Identify prime and composite numbers, GCF, and prime factorization.

Estimating the Margin of Victory for Instant-Runoff Voting

IDENTIFYING FAULT-PRONE MODULES IN SOFTWARE FOR DIAGNOSIS AND TREATMENT USING EEPORTERS CLASSIFICATION TREE

Andreas Fring. Basic Operations

Title: Local Search Required reading: AIMA, Chapter 4 LWH: Chapters 6, 10, 13 and 14.

Fall 2016 COP 3223H Program #5: Election Season Nears an End Due date: Please consult WebCourses for your section

Hoboken Public Schools. College Algebra Curriculum

Hoboken Public Schools. Project Lead The Way Curriculum Grade 8

Chapter 11. Weighted Voting Systems. For All Practical Purposes: Effective Teaching

Hoboken Public Schools. Geometry Curriculum

Maps and Hash Tables. EECS 2011 Prof. J. Elder - 1 -

CS 5523: Operating Systems

File Systems: Fundamentals

Uninformed search. Lirong Xia

Apple s Audio Units Logo License Agreement for Hosting Applications

Do two parties represent the US? Clustering analysis of US public ideology survey

Hoboken Public Schools. AP Statistics Curriculum

The Effectiveness of Receipt-Based Attacks on ThreeBallot

Overview. Ø Neural Networks are considered black-box models Ø They are complex and do not provide much insight into variable relationships

Section Apportionment Methods. Copyright 2013, 2010, 2007, Pearson, Education, Inc.

Cluster Analysis. (see also: Segmentation)

Maps, Hash Tables and Dictionaries

Subreddit Recommendations within Reddit Communities

NEW YORK CITY COLLEGE OF TECHNOLOGY The City University of New York

Hoboken Public Schools. PLTW Introduction to Computer Science Curriculum

Chapter 1: Number Concepts

Deadlock. deadlock analysis - primitive processes, parallel composition, avoidance

Proving correctness of Stable Matching algorithm Analyzing algorithms Asymptotic running times

30 Transformational Design with Essential Aspect Decomposition: Model-Driven Architecture (MDA)

Aspect Decomposition: Model-Driven Architecture (MDA) 30 Transformational Design with Essential. References. Ø Optional: Ø Obligatory:

Optimization Strategies

Political Districting for Elections to the German Bundestag: An Optimization-Based Multi-Stage Heuristic Respecting Administrative Boundaries

Creating and Managing Clauses. Selectica, Inc. Selectica Contract Performance Management System

One View Watchlists Implementation Guide Release 9.2

Year 1 Mental mathematics and fluency in rapid recall of number facts are one of the main aims of the new Mathematics Curriculum.

Mixed-Strategies for Linear Tabling in Prolog

TAFTW (Take Aways for the Week) APT Quiz and Markov Overview. Comparing objects and tradeoffs. From Comparable to TreeMap/Sort

Lab 11: Pair Programming. Review: Pair Programming Roles

Event Based Sequential Program Development: Application to Constructing a Pointer Program

Exploring QR Factorization on GPU for Quantum Monte Carlo Simulation

BMI for everyone. Compsci 6/101: PFTW. Accumulating a value. How to solve an APT. Review how APTs and Python work, run

CoreLogic Matrix Terms of Use & Privacy Policy

1. The augmented matrix for this system is " " " # (remember, I can't draw the V Ç V ß #V V Ä V ß $V V Ä V

Correlations PreK, Kindergarten, First Grade, and Second Grade

30 Transformational Design with Essential Aspect Decomposition: Model-Driven Architecture (MDA)

WORLD INTELLECTUAL PROPERTY ORGANIZATION GENEVA SPECIAL UNION FOR THE INTERNATIONAL PATENT CLASSIFICATION (IPC UNION) AD HOC IPC REFORM WORKING GROUP

DevOps Course Content

Mojdeh Nikdel Patty George

Constraint satisfaction problems. Lirong Xia

Word of the Day Tuesday, September 4, 2018

The Mathematics of Apportionment

COMP : DATA STRUCTURES 2/27/14. Are binary trees satisfying two additional properties:

Instructors: Tengyu Ma and Chris Re

HPCG on Tianhe2. Yutong Lu 1,Chao Yang 2, Yunfei Du 1

Kruskal's MST Algorithm with step-by-step execution

MOS Exams Objective Mapping

Prim's MST Algorithm with step-by-step execution

Protocol to Check Correctness of Colorado s Risk-Limiting Tabulation Audit

OPEN SOURCE CRYPTOCURRENCY

The study of a new gerrymandering methodology

RECOMMENDED CITATION: Pew Research Center, May, 2017, Partisan Identification Is Sticky, but About 10% Switched Parties Over the Past Year

Polydisciplinary Faculty of Larache Abdelmalek Essaadi University, MOROCCO 3 Department of Mathematics and Informatics

Title: Solving Problems by Searching AIMA: Chapter 3 (Sections 3.1, 3.2 and 3.3)

Check off these skills when you feel that you have mastered them. Identify if a dictator exists in a given weighted voting system.

TERMS AND CONDITIONS

WEBSITE TERMS OF USE GLOBAL RESCUE S ( GR OR THE COMPANY ) INTELLECTUAL PROPERTY RIGHTS

Hoboken Public Schools. Algebra I Curriculum

Lecture 8: Verification and Validation

TERMS OF SERVICE Effective Date: March 30 th, 2017

LEGAL TERMS OF USE. Ownership of Terms of Use

This situation where each voter is not equal in the number of votes they control is called:

Probabilistic Latent Semantic Analysis Hofmann (1999)

End User License Agreement for the Accenture HCM Software App

A Calculus for End-to-end Statistical Service Guarantees

Complexity of Manipulating Elections with Few Candidates

Deputy Commissioner for Patent Examination Policy

Coverage tools Eclipse Debugger Object-oriented Design Principles. Oct 26, 2016 Sprenkle - CSCI209 1

Terms of Use. 1. Limited Use

KNOWLEDGE GURU. Player s License Agreement

NON-COMMERCIAL LICENSE AGREEMENT BETWEEN THE REGENTS OF THE UNIVERSITY OF CALIFORNIA AND LICENSEE

The following list of assignments will be completed in your HISTORY NOTEBOOK. Consider them a handbook for understanding the U.S. Constitution!!!

TERMS OF USE COPYRIGHT, TRADEMARK AND OTHER INTELLECTUAL PROPERTY RIGHTS

Chapter. Sampling Distributions Pearson Prentice Hall. All rights reserved

The 2000 U.S. presidential election was a

Measuring a Gerrymander

CORE TECHNOLOGIES CONSULTING, LLC UNLIMITED OEM SOFTWARE LICENSE AGREEMENT

Transcription:

Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking 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.

Recursion Ø Recursion is a fundamental programming technique that can provide elegant solutions certain kinds of problems Ø 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 2

Recursive Thinking Ø Recursion is a programming technique in which a method can call itself to solve a problem Ø 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 Ø 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

Recursive Definitions Ø Consider the following list of numbers: 24, 88, 40, 37 Ø 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 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 number 37 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 loop Ø The non-recursive part often is called the base case 6

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)! Ø The concept of the factorial is defined in terms of another factorial until the base case of 1! is reached 7

Recursive Definitions 5! 5 * 4! 120 24 4 * 3! 6 3 * 2! 2 * 1! 2 1 8

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

Recursive Programming Ø Consider the problem of computing the sum of all the numbers between 1 and any positive integer N, inclusive Ø This problem can be expressed recursively as: N i = 1 N-1 = N + = N + (N-1) + i = 1 N-2 i = 1 = etc. 10

Recursive Programming public int sum (int num) { } int result; if (num == 1) else result = 1; result = num + sum (num - 1); return result; 11

Recursive Programming main result = 6 sum(3) sum result = 3 sum(2) sum result = 1 sum(1) sum 12

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

Recursion vs. Iteration Ø Every recursive solution has a corresponding iterative solution Ø For example, the sum (or the product) of the numbers between 1 and any positive integer N can be calculated with a for loop Ø Recursion has the overhead of multiple method invocations Ø Nevertheless, recursive solutions often are more simple and elegant than iterative solutions 14

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 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 Ø It is often more difficult to trace and debug 15

Indirect Recursion m1 m2 m3 m1 m2 m3 m1 m2 m3 16

Maze Traversal Ø 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 17

Maze Traversal Ø See MazeSearch.java (page 473) Ø See Maze.java (page 474) 18

Towers of Hanoi Ø 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 19

Towers of Hanoi Ø A solution to the three-disk Towers of Hanoi puzzle Ø See Figures 8.5 and 8.6 20

Towers of Hanoi Ø To move a stack of N disks from the original peg to the destination peg 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 Ø 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

Towers of Hanoi Ø See SolveTowers.java (page 479) Ø See TowersOfHanoi.java (page 480) 22

Recursion in Sorting Ø Some sorting algorithms can be implemented recursively Ø We will examine two: Merge sort Quick sort 23

Merge Sort Ø 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) 24

Quick Sort Ø 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

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

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

Fractals Ø See Figure 8.9 Ø See KochSnowflake.java (page 493) Ø See KochPanel.java (page 496) 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