Recursion Chapter 3.5

Similar documents
CSC 344 Algorithms and Complexity. What is Recursion?

PDF created with pdffactory Pro trial version Recursion

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

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

Data Structures and Algorithms " Recursion!

Using Recursion Goodrich, Tamassia. Using Recursion 1

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

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

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

Induction and Recursion. CMPS/MATH 2170: Discrete Mathematics

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

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

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

recursive algorithms 1

Lecture 24 Tao Wang 1

Lecture 10: Recursion vs Iteration

Recursive Definitions

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

CSC 273 Data Structures

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

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

EECS 477: Introduction to algorithms. Lecture 7

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

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Reduction & Recursion Overview

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Unit #3: Recursion, Induction, and Loop Invariants

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

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

Recursion. Fundamentals of Computer Science

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications?

6.001 Notes: Section 4.1

Lecture P6: Recursion

Overview. What is recursion? When one function calls itself directly or indirectly.

STUDENT LESSON A9 Recursion

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

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

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

csci 210: Data Structures Recursion

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

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

Recursion. Chapter 5

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

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

COMP 250 Fall Recursive algorithms 1 Oct. 2, 2017

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

Complexity, Induction, and Recurrence Relations. CSE 373 Help Session 4/7/2016

More Complicated Recursion CMPSC 122

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

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

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05)

Binary Search to find item in sorted array

Programming II (CS300)


CS 310 Advanced Data Structures and Algorithms

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

Recursion. Example R1

Programming II (CS300)

Fun facts about recursion

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

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

COE428 Lecture Notes Week 1 (Week of January 9, 2017)

Recursion. Chapter 7

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

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

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

NCS 301 DATA STRUCTURE USING C

introduction to Programming in C Department of Computer Science and Engineering Lecture No. #40 Recursion Linear Recursion

Data structure and algorithm in Python

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

Programming II (CS300)

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

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

Unit #2: Recursion, Induction, and Loop Invariants

CS 3410 Ch 7 Recursion

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

Solutions to Problem 1 of Homework 3 (10 (+6) Points)

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Solutions to the Second Midterm Exam

Comp 249 Programming Methodology Chapter 11 Recursion

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

This chapter covers recursive definition, including finding closed forms.

CMPSCI 250: Introduction to Computation. Lecture #14: Induction and Recursion (Still More Induction) David Mix Barrington 14 March 2013

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

INSTITUTE OF AERONAUTICAL ENGINEERING

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

Do you remember any iterative sorting methods? Can we produce a good sorting method by. We try to divide and conquer: break into subproblems

Algorithm Design and Recursion. Search and Sort Algorithms

Algorithm Analysis and Design

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

Reading 8 : Recursion

The divide and conquer strategy has three basic parts. For a given problem of size n,

Algorithmics. Some information. Programming details: Ruby desuka?

Fundamental mathematical techniques reviewed: Mathematical induction Recursion. Typically taught in courses such as Calculus and Discrete Mathematics.

Recall from Last Time: Big-Oh Notation

Recursion & Performance. Recursion. Recursion. Recursion. Where Recursion Shines. Breaking a Problem Down

Chapter 13 Recursion. Chapter Objectives

COMP Data Structures

CSC1016. Welcome (again!) Get course notes handout (and read them)

Recursion. Comp Sci 1575 Data Structures. Introduction. Simple examples. The call stack. Types of recursion. Recursive programming

Transcription:

Recursion Chapter 3.5-1 -

Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower of Hanoi Drawbacks and pitfalls of recursion - 2 -

Outcomes By understanding this lecture you should be able to: Use induction to prove the correctness of a recursive algorithm. Identify the base case for an inductive solution Design and analyze linear and binary recursion algorithms Identify the overhead costs of recursion Avoid errors commonly made in writing recursive algorithms - 3 -

Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower of Hanoi Drawbacks and pitfalls of recursion - 4 -

Divide and Conquer When faced with a difficult problem, a classic technique is to break it down into smaller parts that can be solved more easily. Recursion uses induction to do this. - 5 -

History of Induction Implicit use of induction goes back at least to Euclid s proof that the number of primes is infinite (c. 300 BC). The first explicit formulation of the principle is due to Pascal (1665). Euclid of Alexandria, "The Father of Geometry" c. 300 BC Blaise Pascal, 1623-1662 -6-

Induction: Review Induction is a mathematical method for proving that a statement is true for a (possibly infinite) sequence of objects. There are two things that must be proved: 1. The Base Case: The statement is true for the first object 2. The Inductive Step: If the statement is true for a given object, it is also true for the next object. If these two statements hold, then the statement holds for all objects. - 7 -

Induction Example: An Arithmetic Sum Claim: Proof: n i = 1 n(n + 1) n 2 i=0 1. Base Case. The statement holds for n = 0: n i = i =0 0 i = 0 i =0 1 2 n(n + 1) = 1 0(0 + 1) = 0 2 2. Inductive Step. If the claim holds for n = k, then it also holds for n = k+1. k+1 i = k + 1+ i =0 k i = k + 1+ 1 2 k(k + 1) = 1 (k + 1)(k + 2) 2 i =0-8 -

Recursive Divide and Conquer You are given a problem input that is too big to solve directly. You imagine, Suppose I had a friend who could give me the answer to the same problem with slightly smaller input. Then I could easily solve the larger problem. In recursion this friend will actually be another instance (clone) of yourself. Tai (left) and Snuppy (right): the first puppy clone. - 9 -

Friends & Induction Recursive Algorithm: Assume you have an algorithm that works. Use it to write an algorithm that works. If I could get in, I could get the key. Then I could unlock the door so that I can get in. Circular Argument! - 10 - Example from J. Edmonds Thanks Jeff!

Friends & Induction Recursive Algorithm: Assume you have an algorithm that works. Use it to write an algorithm that works. To get into my house I must get the key from a smaller house - 11 -

Friends & Induction Recursive Algorithm: Assume you have an algorithm that works. Use it to write an algorithm that works. The base case Use brute force to get into the smallest house. - 12 -

Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower of Hanoi Drawbacks and pitfalls of recursion - 13 -

Recall: Design Pattern A template for a software solution that can be applied to a variety of situations. Main elements of solution are described in the abstract. Can be specialized to meet specific circumstances. - 14 -

Linear Recursion Design Pattern Test for base cases Begin by testing for a set of base cases (there should be at least one). Every possible chain of recursive calls must eventually reach a base case, and the handling of each base case should not use recursion. Recurse once Perform a single recursive call. (This recursive step may involve a test that decides which of several possible recursive calls to make, but it should ultimately choose to make just one of these calls each time we perform this step.) Define each possible recursive call so that it makes progress towards a base case. - 15 -

Example 1 The factorial function: n! = 1 2 3 (n-1) n Recursive definition: f ( n) = n As a Java method: 1 if n = 0 f ( n 1) else // recursive factorial function public static int recursivefactorial(int n) { if (n == 0) return 1; // base case else return n * recursivefactorial(n- 1); // recursive case } - 16 -

Tracing Recursion - 17 -

Linear Recursion recursivefactorial is an example of linear recursion: only one recursive call is made per stack frame. Since there are n recursive calls, this algorithm has O(n) run time. // recursive factorial function public static int recursivefactorial(int n) { } if (n == 0) return 1; // base case else return n * recursivefactorial(n- 1); // recursive case - 18 -

Example 2: Computing Powers The power function, p(x,n) = x n, can be defined recursively: p(x,n) = 1 if n = 0 x p(x,n 1) otherwise Assume multiplication takes constant time (independent of value of arguments). This leads to a power function that runs in O(n) time (for we make n recursive calls). Can we do better than this? - 19 -

END OF LECTURE 6 JAN 23, 2014-20 -

Recursive Squaring We can derive a more efficient linearly recursive algorithm by using repeated squaring: p(x,n) = 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 x p(x,(n 1) / 2) 2 p(x,n / 2) 2 if n = 0 if n > 0 is odd if n > 0 is even - 21 -

A Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n 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 else y = Power(x, n/ 2) return y y - 22 -

Analyzing the 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 else y = Power(x, n/ 2) return y y Although there are 2 statements that recursively call Power, only one is executed per stack frame. Each time we make a recursive call we halve the value of n (roughly). Thus we make a total of log n recursive calls. That is, this method runs in O(log n) time. - 23 -

Tail Recursion Tail recursion occurs when a linearly recursive method makes its recursive call as its last step. Such a method can easily be converted to an iterative methods (which saves on some resources). - 24 -

Example: Recursively 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 j if i < j then return Swap A[i] and A[ j] ReverseArray(A, i + 1, j - 1) - 25 -

Example: Iteratively Reversing an Array 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 - 26 -

Defining Arguments for Recursion Solving a problem recursively sometimes requires passing additional parameters. ReverseArray is a good example: although we might initially think of passing only the array A as a parameter at the top level, lower levels need to know where in the array they are operating. Thus the recursive interface is ReverseArray(A, i, j). We then invoke the method at the highest level with the message ReverseArray(A, 1, n). - 27 -

Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower of Hanoi Drawbacks and pitfalls of recursion - 28 -

Binary Recursion Binary recursion occurs whenever there are two recursive calls for each non-base case. Example 1: The Fibonacci Sequence - 29 -

The Fibonacci Sequence Fibonacci numbers are defined recursively: F 0 = 0 F 1 = 1 F i = F + i-1 F i-2 for i > 1. The ratio F i / F i 1 converges to ϕ = 1+ 5 2 = 1.61803398874989... (The Golden Ratio ) Fibonacci (c. 1170 - c. 1250) (aka Leonardo of Pisa) - 30 -

The Golden Ratio Two quantities are in the golden ratio if the ratio of the sum of the quantities to the larger quantity is equal to the ratio of the larger quantity to the smaller one. ϕ is the unique positive solution to ϕ = a + b a = a b. - 31 -

The Golden Ratio The Parthenon Leonardo - 32 -

Computing Fibonacci Numbers F 0 = 0 F 1 = 1 F i = F + i-1 F i-2 for i > 1. A recursive algorithm (first attempt): Algorithm BinaryFib(k): Input: Positive integer k Output: The kth Fibonacci number F k if k < 2 then return k else return BinaryFib(k - 1) + BinaryFib(k - 2) - 33 -

Analyzing the Binary Recursion Fibonacci Algorithm Let n k denote number of recursive calls made by BinaryFib(k). Then n 0 = 1 n 1 = 1 n 2 = n 1 + n 0 + 1 = 1 + 1 + 1 = 3 n 3 = n 2 + n 1 + 1 = 3 + 1 + 1 = 5 n 4 = n 3 + n 2 + 1 = 5 + 3 + 1 = 9 n 5 = n 4 + n 3 + 1 = 9 + 5 + 1 = 15 n 6 = n 5 + n 4 + 1 = 15 + 9 + 1 = 25 n 7 = n 6 + n 5 + 1 = 25 + 15 + 1 = 41 n 8 = n 7 + n 6 + 1 = 41 + 25 + 1 = 67. Note that n k more than doubles for every other value of n k. That is, n k > 2 k/2. It increases exponentially! - 34 -

A Better Fibonacci Algorithm Use linear recursion instead: Algorithm LinearFibonacci(k): Input: A positive integer k Output: Pair of Fibonacci numbers (F k, F k-1 ) if k = 1 then return (k, 0) LinearFibonacci(k): F k, F k-1 else (i, j) = LinearFibonacci(k - 1) return (i +j, i) LinearFibonacci(k-1): F k-1, F k-2 Runs in O(k) time. - 35 -

Binary Recursion Second Example: The Tower of Hanoi - 36 -

Example - 37 -

Tower of Hanoi This job of mine is a bit daunting. Where do I start? And I am lazy. Example from J. Edmonds Thanks Jeff! - 38 -

Tower of Hanoi At some point, the biggest disk moves. I will do that job. - 39 -

Tower of Hanoi To do this, the other disks must be in the middle. - 40 -

Tower of Hanoi How will these move? I will get a friend to do it. And another to move these. I only move the big disk. - 41 -

Tower of Hanoi 2 recursive calls! - 42 -

Tower of Hanoi Time: T(1) = 1, T(n) = 1 + 2T(n-1) 2(2T(n-2)) 4(2T(n-3)) 2T(n-1) 4T(n-2) 8T(n-3) 2 i T(n-i) 2 n - 43 -

Binary Recursion: Summary Binary recursion spawns an exponential number of recursive calls. If the inputs are only declining arithmetically (e.g., n-1, n-2, ) the result will be an exponential running time. In order to use binary recursion, the input must be declining geometrically (e.g., n/2, n/4, ). We will see efficient examples of binary recursion with geometricaly declining inputs when we discuss heaps and sorting. - 44 -

Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower of Hanoi Drawbacks and pitfalls of recursion - 45 -

The Overhead Costs of Recursion Many problems are naturally defined recursively. This can lead to simple, elegant code. However, recursive solutions entail a cost in time and memory: each recursive call requires that the current process state (variables, program counter) be pushed onto the system stack, and popped once the recursion unwinds. This typically affects the running time constants, but not the asymptotic time complexity (e.g., O(n), O(n 2 ) etc.) Thus recursive solutions may still be preferred unless there are very strict time/memory constraints. - 46 -

The Curse in Recursion: Errors to Avoid // recursive factorial function public static int recursivefactorial(int n) { return n * recursivefactorial(n- 1); } There must be a base condition: the recursion must ground out! - 47 -

The Curse in Recursion: Errors to Avoid // recursive factorial function public static int recursivefactorial(int n) { if (n == 0) return recursivefactorial(n); // base case else return n * recursivefactorial(n- 1); // recursive case } The base condition must not involve more recursion! - 48 -

The Curse in Recursion: Errors to Avoid // recursive factorial function public static int recursivefactorial(int n) { } if (n == 0) return 1; // base case else return (n 1) * recursivefactorial(n); // recursive case The input must be converging toward the base condition! - 49 -

Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower of Hanoi Drawbacks and pitfalls of recursion - 50 -

Outcomes By understanding this lecture you should be able to: Use induction to prove the correctness of a recursive algorithm. Identify the base case for an inductive solution Design and analyze linear and binary recursion algorithms Identify the overhead costs of recursion Avoid errors commonly made in writing recursive algorithms - 51 -

END OF LECTURE 7 JAN 28, 2014-52 -