CS159. Nathan Sprague. November 9, 2015

Similar documents
CS103L SPRING 2017 UNIT 8: RECURSION

Fun facts about recursion

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

More Complicated Recursion CMPSC 122

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

CS 206 Introduction to Computer Science II

Greedy Algorithms and Huffman Coding

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

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

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

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

Binary Trees. Recursive definition. Is this a binary tree?

Chapter 18 Recursion. Motivations

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

Programming II (CS300)

Lecture 6 Sorting and Searching

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

CSCI 2212: Intermediate Programming / C Recursion

CS159. Nathan Sprague

An introduction to Scheme

Search,Sort,Recursion

CSE 230 Computer Science II (Data Structure) Introduction

pset1: C Tommy MacWilliam Grading Getting Started pset1: C Style Pennies Greedy Chart September 11, 2011

Goals: Define computational problem instance of a computational problem algorithm pseudocode Briefly discuss recursive procedure big-o notation

Recursion. Chapter 11. Chapter 11 1

Programming II (CS300)

CS 206 Introduction to Computer Science II

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

CS302: Self Check Quiz 2

QUIZ. 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different?

Module 08: Searching and Sorting Algorithms

C/C++ Programming Lecture 18 Name:

Loops. When to Use Loops

How many ways to make 50 cents? first-denomination Solution. CS61A Lecture 5. count-change. cc base cases. How many have you figured out?

Programming II (CS300)

COMP 110 Practice Exercises for Midterm Solutions

CS171 Midterm Exam. October 29, Name:

Recursive Algorithms. We would like to write an algorithm that computes the factorial of a given non-negative integer number n.

CSL 201 Data Structures Mid-Semester Exam minutes

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

ITI Introduction to Computing II

Introduction to Computers & Programming

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

ECE608 - Chapter 16 answers

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

An algorithm is a sequence of instructions that one must perform in order to solve a wellformulated

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

cs Java: lecture #6

Tail Recursion: working from the beginning towards the end.

CS205: Scalable Software Systems

CS159. Nathan Sprague

Data structure and algorithm in Python

Why use recursion? Some problems are more easily expressed in a recursive definition

CS 163 Practice Final Exam Winter 2012

QuickSort

User-defined Functions. Conditional Expressions in Scheme

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

Backtracking. See Section 7.7 p of Weiss

Recursion: Recursion: repeated curses

CS302 - Data Structures using C++

Prerequisites: Read all chapters through Chapter 4 in the textbook before attempting this lab. Read through this entire assignment before you begin.

CS201 Discussion 7 MARKOV AND RECURSION

Recursion Problems. Warm Ups. Enumeration 1 / 7

Analysis of Searching Algorithms

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

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

AQA Computer Science A-Level Searching algorithms Advanced Notes

School of Informatics, University of Edinburgh

CS 115 Exam 3, Fall 2011

Pseudo code of algorithms are to be read by.

CSC 1351: Quiz 6: Sort and Search

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

Data Structures and Algorithms. Dynamic Programming

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

Unit 10: Sorting/Searching/Recursion

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

CS 106 Introduction to Computer Science I

Give a short answer (i.e. 1 to 3 sentences) for the following questions:

ITEC2620 Introduction to Data Structures

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

Computer Science 385 Design and Analysis of Algorithms Siena College Spring Topic Notes: Dynamic Programming

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Lecture. Algorithm Design and Recursion. Richard E Sarkis CSC 161: The Art of Programming

CS64 Week 5 Lecture 1. Kyle Dewey

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

RECURSION. Problem Solving with Computers-II 6

Unit-2 Divide and conquer 2016

C22a: Problem Solving using Recursion

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Analyzing Complexity of Lists

Name Section: M/W T/TH Number Definition Matching (8 Points)

CS 151. Recursion (Review!) Wednesday, September 19, 12

Recursion. Recursion is: Recursion splits a problem:

CMPSCI 187: Programming With Data Structures. Lecture #16: Thinking About Recursion David Mix Barrington 12 October 2012

1.7 Recursion. Department of CSE

Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

Tutorial 7: Advanced Algorithms. (e) Give an example in which fixed-parameter tractability is useful.

Points off Total off Net Score. CS 314 Final Exam Spring 2016

Transcription:

CS159 Nathan Sprague November 9, 2015

Recursive Definitions Merriam Websters definition of Ancestor: Ancestor One from whom a person is descended [...] Here is a recursive version: Ancestor One s parent. or A parent of an ancestor.

Recursively Defined Functions Classic example is the factorial function: n! if n = 0 then n! = 1 (basis or initial conditions) if n > 0 then n! = n (n 1)!

Recursive Methods / Recursive Programming A recursive method is a method that includes a call to itself. It is often straightforward to compute recursively defined functions using recursive methods: 1 int factorial ( int n) 2 { 3 int value ; 4 5 if (n == 0) 6 value = 1; 7 else 8 value = n * factorial ( n - 1); 9 10 return value ; 11 }

Activation Records Every method call results in an activation record which contains: Local variables and their values. The location (in the caller) of the call.

Tracing Recursive Methods...

Recursion is Not Always the Best Approach 1 int factorial ( int n) 2 { 3 int value = 1; 4 5 for ( int i =2; i <= n; i ++) 6 { 7 value *= i; 8 } 9 10 return value ; 11 }

Recursive Problem Solving Recursion is often a good idea when a problem can be solved by breaking it into one or more smaller problems of the same form. The process is: Figure out how to solve the easy case, i.e. the base case. Figure out how to move the hard case toward the easy case.

Recursion Pseudocode 1 Nearly every recursive method ends up looking like the following: 2 recursivemethod ( input ) 3 { 4 if ( input represents a base case ) 5 { 6 handle the base case directly. 7 } 8 else 9 { 10 call recursivemethod one or more times 11 passing it only part of the input. 12 } 13 } There may be more than one base case.

Recursion Pseudocode Variations Sometimes there is nothing to do for the base case. We just want to stop: 1 recursivemethod ( input ) 2 { 3 if ( input is NOT the base case ) 4 { 5 call recursivemethod one or more times 6 passing it only part of the input. 7 } 8 9 // No else statement. Nothing to do for the base case. 10 }

Example: Binary Search Searching for a particular value in a sorted array. (More than one base case.) 1 public static int binarysearch ( int [] array, int first, int last, int value ) 2 { 3 int mid ; 4 5 if ( first > last ) // Easy /Base case. No elements left. Failure! 6 { 7 return - 1; 8 } 9 10 mid = ( first + last ) / 2; 11 12 if ( array [mid ] == value ) // Another base case. Success! 13 { 14 return mid ; 15 } 16 else if ( array [mid ] < value ) 17 { 18 return binarysearch ( array, mid + 1, last, value ); 19 } 20 else 21 { 22 return binarysearch ( array, first, mid - 1, value ); 23 } 24 }

Aside: Tail Recursion A method is tail recursive if the recursive call is the final operation. It is straightforward to replace tail recursion with a while-loop. If a recursive method is not tail-recursive, then the call stack is doing important work: saving the state of an ongoing computation so that it can resume when the recursive call completes.

Aside: Tail Recursion A method is tail recursive if the recursive call is the final operation. It is straightforward to replace tail recursion with a while-loop. If a recursive method is not tail-recursive, then the call stack is doing important work: saving the state of an ongoing computation so that it can resume when the recursive call completes. Was the factorial method we saw earlier tail recursive?

Aside: Tail Recursion A method is tail recursive if the recursive call is the final operation. It is straightforward to replace tail recursion with a while-loop. If a recursive method is not tail-recursive, then the call stack is doing important work: saving the state of an ongoing computation so that it can resume when the recursive call completes. Was the factorial method we saw earlier tail recursive? No. Multiplication occurs after the recursive call.

Iterative Binary Search 1 public static int binarysearchiterative ( int [] array, int value ) 2 { 3 int first, last, mid, result ; 4 boolean found ; 5 6 first = 0; 7 last = array. length - 1; 8 9 result = -1; 10 found = false ; 11 12 while ( first <= last &&! found ) // Check for "base cases " 13 { 14 mid = ( first + last ) / 2; 15 if ( array [mid ] == value ) 16 { 17 result = mid ; 18 found = true ; 19 } 20 else if ( array [mid ] < value ) 21 { 22 first = mid + 1; // " Recursively " search right 23 } 24 else 25 { 26 last = mid - 1; // " Recursively " search left 27 } 28 } 29 30 return result ; 31 }

The Coin Problem Problem: determine the minimum number of coins needed to make change for a given amount. E.g. we have pennies, nickels and dimes, and we need to 7 cents worth of change. How many coins will it take? Pseudocode: If the change amount is equal to a coin denomination. Return 1; // Base case! only one coin is needed. Otherwise consider every possible way of breaking the change amount in two. Each split results in two smaller versions of the change problem. Solve the recursively, add the results, and return the lowest sum. E.g. if the amount is 7 cents we can try: 1 and 6 1 + 2 = 3 2 and 5 2 + 1 = 3 3 and 4 3 + 4 = 7