Solving problems by recursion

Similar documents
Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Recursion continued. Programming using server Covers material done in Recitation. Part 2 Friday 8am to 4pm in CS110 lab

1 Recursion. 2 Recursive Algorithms. 2.1 Example: The Dictionary Search Problem. CSci 235 Software Design and Analysis II Introduction to Recursion

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

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

recursive algorithms 1

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

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

EE 368. Weeks 4 (Notes)

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

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

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

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

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

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

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

CSE 214 Computer Science II Recursion

Recursive Definitions

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

Massachusetts Institute of Technology Department of Mechanical Engineering

Lecture 8 Recursion. The Mirrors

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

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

1.7 Recursion. Department of CSE

Programming with Recursion. What Is Recursion?

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

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

Complexity of Algorithms

Blowing a gasket. Recursion. Classic recursive examples. CS112 Scientific Computation Department of Computer Science Wellesley College

CSE 2123 Recursion. Jeremy Morris

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

Recursion. Chapter 5

Recursion. Chapter 2. Objectives. Upon completion you will be able to:

CS103L SPRING 2017 UNIT 8: RECURSION

Instructors: Daniel Deutch, Amir Rubinstein, Teaching Assistants: Amir Gilad, Michal Kleinbort

Data Structures And Algorithms

UNIT 5A Recursion: Basics. Recursion

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

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

Chapter 15: Recursion

C22a: Problem Solving using Recursion

Recursion. Chapter 7

Announcement. Submit assignment 3 on CourSys Do not hand in hard copy Due Friday, 15:20:00. Caution: Assignment 4 will be due next Wednesday

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

Programming II (CS300)

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Recursion. Chapter 11. Chapter 11 1

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

Recursion. Chapter 17 CMPE13. Cyrus Bazeghi

Introduction to Computers & Programming

Programming II (CS300)

Reading 8 : Recursion

2: Complexity and Recursion

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

Programming II (CS300)

Sorting & Searching (and a Tower)

Recursion: The Mirrors. (Walls & Mirrors - Chapter 2)

Recursion. notes Chapter 8

Recursive Definitions and Structural Induction

Recursion vs Induction

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

CS 506, Sect 002 Homework 5 Dr. David Nassimi Foundations of CS Due: Week 11, Mon. Apr. 7 Spring 2014

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


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

Recursive Problem Solving

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

Recursion. Example R1

Chapter 2. Question 2 Write a box trace of the function given in Checkpoint Question 1. We trace the function with 4 as its argument (see next page).

Search,Sort,Recursion

Recursion vs Induction. CS3330: Algorithms The University of Iowa

Recursion. February 02, 2018 Cinda Heeren / Geoffrey Tien 1

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

Chapter 13 Recursion. Chapter Objectives

Recursion Chapter 3.5

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)

Population Problems. To develop a model for population growth, To develop proficiency with algebraic equations

UNIT 5A Recursion: Basics. Recursion

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique.

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

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

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

CSE 230 Intermediate Programming in C and C++ Recursion

CS200: Recursion and induction (recap from cs161)

i.e.: n! = n (n 1)

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

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

Chapter 17 Recursion

UNIT 5C Merge Sort Principles of Computing, Carnegie Mellon University

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

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

Bachelor Level/ First Year/ Second Semester/ Science Full Marks: 60 Computer Science and Information Technology (CSc. 154) Pass Marks: 24

CS/CE 2336 Computer Science II

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

Algorithm classification

Copyright The McGraw-Hill Companies, Inc. Persion required for reproduction or display. What is Recursion?

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

Programming and Data Structure

Lecture 24 Tao Wang 1

Transcription:

Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem into simpler problems Sometimes, the simpler problem is similar to (but smaller than) the original problem Example: factorials It s hard to calculate 24! directly, but we could just calculate 23! and multiply by 24 This technique is called recursion Often involves a method calling itself! May call itself one or more times Must have an ending point! Dictionary Search Want to look up a word in the dictionary Could start at beginning until I find the word Could look in the middle, and then decide which half to look in First approach is called a linear search Second approach is called a binary search: search( dictionary, myword ) { if the word in the middle is myword then done else if ( myword < word ) search( first half of dictionary, myword ) else search( second half of dictionary, myword )

Efficiency How much does it 'cost' to find the word using each algorithm? We can think of cost as the number of operations required to perform an algorithm. Linear search Dictionary size / 2 on average Binary search log 2 ( Dictionary Size ) We can use Big 'O' notation describe the 'order' of an algorithm Linear search O( n ) 'order n' Binary search O( log 2 n ) 'order log n' Four Questions for Constructing Recursive Solutions How can you define the problem in terms of a smaller problem of the same type? How does each recursive call diminish the size of the problem? What instance of the problem can serve as the base case? As the problem size diminishes, will you reach the base case? Factorials by recursion Easy way to calculate n! n! = 1 if n == 1 Otherwise, n! = n * (n-1)! There are two important things here Each step reduces the size of the problem There is a definite stopping point This point must be reached! For this example, there are more efficient ways to do this problem intx; else { x = factorial(n-1); return (n * x); 6 factorial(3) n = 3 x =? factorial(2) n = 2 x =? 2 factorial(1) n = 1 1

Some 'facts' about rabbits Rabbits never die A rabbit can start reproducing at the beginning of its third month of life Rabbits are always born in male/female pairs. At the beginning of each month, every mature female rabbit gives birth to one male/female pair of rabbits. So, if we start with 1 pair of newborn rabbits: Month 1: 1 pair Month 2: 1 pair Month 3: 2 pairs the original pair gave birth Month 4: 3 pairs the original pair gave birth again Month 5: 5 pairs the original pair and its first offspring both gave birth Month 6: 8 pairs the 3 pairs alive in Month 4 gave birth Fibonacci numbers Definition F n = F n-1 + F n-2 F 0 = F 1 = 1 How can we solve this recursively? Calculate fibonacci(n-1) Calculate fibonacci(n-2) Add the two together This works! Problem reduced to smaller problem Definite stopping point (always reached) Again, there are more efficient ways to do this intfibonacci(int n) { int,; if(n <= 1) { else { = fibonacci(n-1); = fibonacci(n-2); return (+); How can a function exist many times? Example: fibonacci(n) calls fibonacci( ) twice How does the computer keep track of this? Solution: keep information on a stack Done automatically by the compiler / run-time system Stack grows in length as needed Each method s local information is kept in an activation record Local variables Reference to activation record of method that called this one Activation record cleaned up after method returns fibonacci(3) fibonacci(2) fibonacci(1) Memory n=3 n=2 n=1

Towers of Hanoi Problem: move tower from one peg to another May only move one disk at a time May only place a disk on top of a larger disk May use (currently) empty peg as a holding area Solve the problem for an n-disk tower by Moving the n-1 top disks from left to middle peg Moving the bottom (largest) disk from left to right peg Moving the n-1 tower from middle to right peg Can we do this? Solving Towers of Hanoi with recursion Two cases Tower has exactly one disk Move it from source to destination Tower has more than one disk Move the top n-1 disks to the holding peg Move the bottom disk Move the top n-1 disks from holding peg to destination Important! Holding peg is same at start and end of each move Top disk on holding peg is larger than any disk in tower being moved movetower (intfrompeg, inttopeg, int holdpeg, int n) { movedisk (frompeg,topeg,1); else { movetower(frompeg,holdpeg, topeg,n-1); movedisk(frompeg,topeg,n); movetower(holdpeg,topeg, frompeg,n-1); movedisk(intfrom,intto,intn) { // Move disk from peg from to //peg to What else can we use recursion for? Generic problem type: divide-and-conquer Break a problem into 2 (or more) smaller pieces Each piece is similar to the original problem, but smaller Solve each piece individually Combine the results Divide-and-conquer is best implemented with recursion Relatively small code Low code complexity: let the system stack handle all of the details May be easy to convert some forms of recursion, though

Converting tail recursion into a loop Factorials can be solved with recursion N! = (N-1)! * N This is recursive, but can be rewritten as N * (N-1)! The last thing the method does is call itself! This is called tail recursion Tail recursion can (usually) be converted into a loop easily By the time the tail recursion occurs, none of the variables in the method are needed This means they can be overwritten! Rather than calling the method recursively, simply return to the top with a new parameter Example: tail recursion for factorials Multiplications are done in the order 2,3,4, Calls are made in the reverse order Multiplication comes after the call Straighten out the recursion to make it more efficient intx; else { x = factorial(n-1); return (n * x); intx = 1; for (j=1;j<=n;j++) { x = j*x; return (x); Using recursion Many recursive routines may be simplified, but Many cannot be made simpler It s very hard to do Towers of Hanoi without recursion Doing Towers of Hanoi non-recursively requires several stacks why not let the system manage them? General rule of thumb: If it s obvious how to do it non-recursively, do it that way If recursion makes programming easier, take advantage of it Example: Fibonacci sequence This can be easily straightened by simply keeping track of the previous two Fibonacci numbers This is a (very) simple stack, and easy to implement Many sorting and tree algorithms use recursion for ease of implementation and understanding (more on this in the next week)