Recursion. The Recursion Pattern. Recursion 3/16/14

Similar documents
RECURSION (CH 5) A pattern for solving algorithm design problems

Using Recursion Goodrich, Tamassia. Using Recursion 1

Using Recursion. Linear Recursion ( 4.1.1) Recall the Recursion Pattern ( 2.5) A Simple Example of Linear Recursion

Data Structures and Algorithms " Recursion!

Linked Lists. Outline. COMP9024: Data Structures and Algorithms. Algorithms versus Heuristics. Data Structures and Algorithms. Abstract Data Types

CSC 344 Algorithms and Complexity. What is Recursion?

PDF created with pdffactory Pro trial version Recursion

Recursion Chapter 3.5

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

Data structure and algorithm in Python

NCS 301 DATA STRUCTURE USING C

Definitions. You can represent a point by a dot and name it by a capital letter.

Divide-and-Conquer. Divide-and conquer is a general algorithm design paradigm:

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

csci 210: Data Structures Stacks and Queues in Solution Searching

Algorithm Design and Recursion. Search and Sort Algorithms

Quick-Sort. Quick-sort is a randomized sorting algorithm based on the divide-and-conquer paradigm:

Euclid. Father of Geometry Euclidean Geometry Euclid s Elements

8/19/2014. Most algorithms transform input objects into output objects The running time of an algorithm typically grows with input size

Discrete Mathematics Introduction

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

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

Lecture 6: Recursion RECURSION

Chapter 1: Number and Operations

Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

Bucket-Sort and Radix-Sort

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

Entry and Priority Queue ADTs

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

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

Data Structures and Algorithms

Flowchart & Algorithm

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

Bucket-Sort and Radix-Sort

142

SORTING AND SELECTION

Algorithms 4. Odd or even Algorithm 5. Greatest among three numbers Algorithm 6. Simple Calculator Algorithm

Chapter Summary. Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms

Comp 249 Programming Methodology Chapter 11 Recursion

Finite Math - J-term Homework. Section Inverse of a Square Matrix

Sorting Goodrich, Tamassia Sorting 1

9/10/2018 Algorithms & Data Structures Analysis of Algorithms. Siyuan Jiang, Sept

Recursion: Recursion: repeated curses

Lecture P6: Recursion

GEOMETRY BASIC GEOMETRICAL IDEAS. 3) A point has no dimensions (length, breadth or thickness).

For searching and sorting algorithms, this is particularly dependent on the number of data elements.

TOURNAMENT OF THE TOWNS, Glossary

CSE 373 Lecture 19: Wrap-Up of Sorting


Lecture 4. Hashing Methods

Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. 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

EECS1012. Net-centric Introduction to Computing. Lecture 7 Computational Thinking. Fall 2018, EECS York University. M.S. Brown and Amir H.

DIVIDE AND CONQUER ALGORITHMS ANALYSIS WITH RECURRENCE EQUATIONS

2.6 BOOLEAN FUNCTIONS

UAB MATH TALENT SEARCH

AVL Tree Definition. An example of an AVL tree where the heights are shown next to the nodes. Adelson-Velsky and Landis

e-pg PATHSHALA- Computer Science Design and Analysis of Algorithms Module 14 Component-I (A) - Personal Details

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

Fundamentals of Programming Session 13

Proving Triangles and Quadrilaterals Satisfy Transformational Definitions

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

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

More Complicated Recursion CMPSC 122

Recursive Definitions

Logical Coding, algorithms and Data Structures

Math Circle Beginners Group January 17, 2016 Geometry II

6.001 Notes: Section 4.1

MAT 243 Test 2 SOLUTIONS, FORM A

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

Priority Queue Sorting

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Betweenness and the Crossbar Theorem. Lemma: Let A, B, and C be distinct points. If A*B*C, then neither A*C*B nor B*A*C.

[Y2] Counting and understanding number. [Y2] Counting and understanding number. [Y2] Counting and understanding number

Programming II (CS300)

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Complementary, Supplementary, & Vertical Angles

Recursion (Rosen, 6 th edition, Section 4.3, 4.4)

8 Algorithms 8.1. Foundations of Computer Science Cengage Learning

Loops / Repetition Statements

Chapter 8 Algorithms 1

CSC 273 Data Structures

Lines and Angles. Chapter INTRODUCTION

Reduction & Recursion Overview

1a. [4 marks] A surveyor has to calculate the area of a triangular piece of land, DCE.

no triangle can have more than one right angle or obtuse angle.

CSCE 110 Notes on Recursive Algorithms (Part 12) Prof. Amr Goneid

1. (15 points) Solve the decanting problem for containers of sizes 199 and 179; that is find integers x and y satisfying.

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Programming II (CS300)

CS 2230 CS II: Data structures. Limits of comparison sorting, beyond comparison sorting Brandon Myers University of Iowa

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

Programming II (CS300)

CSC Design and Analysis of Algorithms. Lecture 5. Decrease and Conquer Algorithm Design Technique. Decrease-and-Conquer

HL Maths Junior Certificate Notes by Bronte Smith

1. General Computer Questions

Functional programming with Common Lisp

Parallel Sorting Algorithms

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

Transcription:

Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Recursion Recursion 1 The Recursion Pattern Recursion: when a method calls itself Classic example the factorial function: n! = 1 2 3 (n-1) n Recursive definition: As a Java method: 1 if n = 0 f ( n) = n f ( n 1) Recursion 2 1

Content of a Recursive Method Base case(s) n Values of the input variables for which we perform no recursive calls are called base cases (there should be at least one base case). n Every possible chain of recursive calls must eventually reach a base case. Recursive calls n Calls to the current method. n Each recursive call should be defined so that it makes progress towards a base case. 2014 Goodrich, Tamassia, Recursion Goldwasser 3 Visualizing Recursion Recursion trace n A box for each recursive call n An arrow from each caller to callee n An arrow from each callee to caller showing return value Example call recursivefactorial ( 4 ) call recursivefactorial ( 3 ) call recursivefactorial ( 2 ) call recursivefactorial ( 1 ) return 4 * 6 = 24 return 3 * 2 = 6 return 2 * 1 = 2 return 1 * 1 = 1 final answer call return 1 recursivefactorial ( 0 ) 2014 Goodrich, Tamassia, Recursion Goldwasser 4 2

Example: English Ruler Print the ticks and numbers like an English ruler: 2014 Goodrich, Tamassia, Recursion Goldwasser 5 Using Recursion Slide by Matt Stallmann included with permission. drawinterval(length) Input: length of a tick Output: ruler with tick of the given length in the middle and smaller rulers on either side drawinterval(length) if( length > 0 ) then drawinterval ( length - 1 ) draw line of the given length drawinterval ( length - 1 ) Recursion 6 3

Recursive Drawing Method The drawing method is based on the following recursive definition An interval with a central tick length L >1 consists of: n An interval with a central tick length L-1 n An single tick of length L n An interval with a central tick length L-1 Recursion 7 A Recursive Method for Drawing Ticks on an English Ruler Note the two recursive calls Recursion 8 4

Binary Search Search for an integer in an ordered list Recursion 9 Visualizing Binary Search We consider three cases: n If the target equals data[mid], then we have found the target. n If target < data[mid], then we recur on the first half of the sequence. n If target > data[mid], then we recur on the second half of the sequence. Recursion 10 5

Analyzing Binary Search Runs in O(log n) time. n The remaining portion of the list is of size high low + 1 n After one comparison, this becomes one of the following: n Thus, each recursive call divides the search region in half; hence, there can be at most log n levels Recursion 11 Linear Recursion Test for base cases n Begin by testing for a set of base cases (there should be at least one). n Every possible chain of recursive calls must eventually reach a base case, and the handling of each base case should not use recursion. Recur once n Perform a single recursive call n This step may have a test that decides which of several possible recursive calls to make, but it should ultimately make just one of these calls n Define each possible recursive call so that it makes progress towards a base case. Recursion 12 6

Example of Linear Recursion Algorithm linearsum(a, n): Input: Array, A, of integers Integer n such that 0 n A Output: Sum of the first n integers in A if n = 0 then return 0 return linearsum(a, n - 1) + A[n - 1] Recursion trace of linearsum(data, 5) called on array data = [4, 3, 6, 2, 8] Recursion 13 Reversing an Array Algorithm reversearray(a, i, j): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at if i < j then Swap A[i] and A[ j] reversearray(a, i + 1, j - 1) return Recursion 14 7

Defining Arguments for Recursion In creating recursive methods, it is important to define the methods in ways that facilitate recursion. This sometimes requires we define additional parameters that are passed to the method. For example, we defined the array reversal method as reversearray(a, i, j), not reversearray(a) Recursion 15 Computing Powers The power function, p(x,n)=x n, can be defined recursively: # 1 p( x, n) = "! x p( x, n 1) if n = 0 This leads to an power function that runs in O(n) time (for we make n recursive calls) We can do better than this, however Recursion 16 8

Recursive Squaring We can derive a more efficient linearly recursive algorithm by using repeated squaring: p( x, n) = x p( x,( n 1) / 2) p( x, n / 2) For example, 2 4 = 2 (4/2)2 = (2 4/2 ) 2 = (2 2 ) 2 = 4 2 = 16 2 5 = 2 1+(4/2)2 = 2(2 4/2 ) 2 = 2(2 2 ) 2 = 2(4 2 ) = 32 2 6 = 2 (6/ 2)2 = (2 6/2 ) 2 = (2 3 ) 2 = 8 2 = 64 2 7 = 2 1+(6/2)2 = 2(2 6/2 ) 2 = 2(2 3 ) 2 = 2(8 2 ) = 128 1 2 2 if x = 0 if x > 0 is odd if x > 0 is even Recursion 17 Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value x n if n = 0 then return 1 if n is odd then y = Power(x, (n - 1)/ 2) return x y y y = Power(x, n/ 2) return y y Recursion 18 9

Analysis Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value x n if n = 0 then return 1 if n is odd then y = Power(x, (n - 1)/ 2) return x y y y = Power(x, n/ 2) return y y Each time we make a recursive call we halve the value of n; hence, we make log n recursive calls. That is, this method runs in O(log n) time. It is important that we use a variable twice here rather than calling the method twice. Recursion 19 Tail Recursion Tail recursion occurs when a linearly recursive method makes its recursive call as its last step. The array reversal method is an example. Such methods can be easily converted to nonrecursive methods (which saves on some resources). Example: Algorithm IterativeReverseArray(A, i, j ): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j while i < j do Swap A[i ] and A[ j ] i = i + 1 j = j - 1 return Recursion 20 10

Binary Recursion Binary recursion occurs whenever there are two recursive calls for each non-base case. Example from before: the drawinterval method for drawing ticks on an English ruler. Recursion 21 Another Binary Recusive Method Problem: add all the numbers in an integer array A: Algorithm BinarySum(A, i, n): Input: An array A and integers i and n Output: The sum of the n integers in A starting at index i if n = 1 then return A[i] return BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2) Example trace: 0, 8 0, 4 4, 4 0, 2 2, 2 4, 2 6, 2 0, 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1 Recursion 22 11

Computing Fibonacci Numbers Fibonacci numbers are defined recursively: F 0 = 0 F 1 = 1 F i = F i-1 + F i-2 for i > 1. Recursive algorithm (first attempt): Algorithm BinaryFib(k): Input: Nonnegative integer k Output: The kth Fibonacci number F k if k = 1 then return k return BinaryFib(k - 1) + BinaryFib(k - 2) Recursion 23 Analysis Let n k be the number of recursive calls by BinaryFib(k) n n 0 = 1 n n 1 = 1 n n 2 = n 1 + n 0 + 1 = 1 + 1 + 1 = 3 n n 3 = n 2 + n 1 + 1 = 3 + 1 + 1 = 5 n n 4 = n 3 + n 2 + 1 = 5 + 3 + 1 = 9 n n 5 = n 4 + n 3 + 1 = 9 + 5 + 1 = 15 n n 6 = n 5 + n 4 + 1 = 15 + 9 + 1 = 25 n n 7 = n 6 + n 5 + 1 = 25 + 15 + 1 = 41 n n 8 = n 7 + n 6 + 1 = 41 + 25 + 1 = 67. Note that n k at least doubles every other time That is, n k > 2 k/2. It is exponential! Recursion 24 12

A Better Fibonacci Algorithm Use linear recursion instead Algorithm LinearFibonacci(k): Input: A nonnegative integer k Output: Pair of Fibonacci numbers (F k, F k-1 ) if k = 1 then return (k, 0) (i, j) = LinearFibonacci(k - 1) return (i +j, i) LinearFibonacci makes k-1 recursive calls Recursion 25 Multiple Recursion Motivating example: n summation puzzles w pot + pan = bib w dog + cat = pig w boy + girl = baby Multiple recursion: n makes potentially many recursive calls n not just one or two Recursion 26 13

Algorithm for Multiple Recursion Algorithm PuzzleSolve(k,S,U): Input: Integer k, sequence S, and set U (universe of elements to test) Output: Enumeration of all k-length extensions to S using elements in U without repetitions for all e in U do Remove e from U {e is now being used} Add e to the end of S if k = 1 then Test whether S is a configuration that solves the puzzle if S solves the puzzle then return Solution found: S PuzzleSolve(k - 1, S,U) Add e back to U {e is now unused} Remove e from the end of S Recursion 27 Example cbb + ba = abc 799 + 98 = 997 [] {a,b,c} Slide by Matt Stallmann included with permission. a,b,c stand for 7,8,9; not necessarily in that order [a] {b,c} a=7 [b] {a,c} b=7 [c] {a,b} c=7 [ab] {c} a=7,b=8 c=9 [ac] {b} a=7,c=8 b=9 [ca] {b} c=7,a=8 b=9 [cb] {a} c=7,b=8 a=9 [ba] {c} b=7,a=8 c=9 [bc] {a} b=7,c=8 a=9 might be able to stop sooner Recursion 28 14

Visualizing PuzzleSolve Initial call PuzzleSolve ( 3, (),{ a, b, c } ) PuzzleSolve ( 2, a,{ b, c } ) PuzzleSolve ( 2, b,{ a, c } ) PuzzleSolve ( 2, c,{ a, b } ) PuzzleSolve ( 1, ab,{ c }) PuzzleSolve ( 1, ba,{ c }) PuzzleSolve ( 1, ca,{ b }) abc PuzzleSolve ( 1, ac,{ b }) bac PuzzleSolve ( 1, bc,{ a }) cab PuzzleSolve ( 1, cb,{ a }) acb bca cba Recursion 29 15