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

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

Function Call Example

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

Lecture 24 Tao Wang 1

Comp 249 Programming Methodology Chapter 11 Recursion

Recursion CHAPTER THINKING RECURSIVELY 669 Recursive Design Techniques 669 Binary Search 671 Efficiency of Binary Search 677

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

Chapter 17 - Notes Recursion

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

Recursion. Chapter 11. Chapter 11 1

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Recursion. Chapter 11

Fun facts about recursion

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

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CSCE 206: Structured Programming in C++

Unit #2: Recursion, Induction, and Loop Invariants

Unit #3: Recursion, Induction, and Loop Invariants

Absolute C++ Walter Savitch

Chapter 10 - Notes Applications of Arrays

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

Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort

REPETITION CONTROL STRUCTURE LOGO

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Programming II (CS300)

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

Introduction to the Analysis of Algorithms. Algorithm

Data structure and algorithm in Python

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018

Exceptions, Case Study-Exception handling in C++.

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

10/25/ Recursion. Objectives. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

PDF created with pdffactory Pro trial version Recursion

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution

Recursion Chapter 3.5

! Search: find an item in an array, return the. ! Sort: rearrange the items in an array into some. ! There are various methods (algorithms) for

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

Programming II (CS300)

FORM 2 (Please put your name and form # on the scantron!!!!)

Data Structures Lecture 3 Order Notation and Recursion

CSCI 104 Runtime Complexity. Mark Redekopp David Kempe

CS103 Unit 8. Recursion. Mark Redekopp

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Section 1: True / False (2 points each, 30 pts total)

CS171 Midterm Exam. October 29, Name:

Lecture 6 Sorting and Searching

Recursion. Chapter 7

Introduction to Programming

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

CS103 Unit 8. Recursion. Mark Redekopp

PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS

Problem Solving with C++

Algorithm Analysis and Design

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

Topics. Functions. Functions

Quiz 0 Review Session. October 13th, 2014

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

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

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

Programming II (CS300)

Chapter 3 - Functions

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

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

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Search,Sort,Recursion

Objectives. Recursion. One Possible Way. How do you look up a name in the phone book? Recursive Methods Must Eventually Terminate.

CS 216 Fall 2007 Midterm 1 Page 1 of 10 Name: ID:

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

do { statements } while (condition);

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

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

Computer Programming

2. Functions I: Passing by Value

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Why Is Repetition Needed?

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

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

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

Lecture 15 Binary Search Trees

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures. Recursive design. Convert loops to recursion

Algorithm Complexity Analysis: Big-O Notation (Chapter 10.4) Dr. Yingwu Zhu

Lecture Notes for Chapter 2: Getting Started

Programming Language. Functions. Eng. Anis Nazer First Semester

C Functions. Object created and destroyed within its block auto: default for local variables

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

1 Unit 8 'for' Loops

STUDENT LESSON A9 Recursion

CSI33 Data Structures

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

AN OVERVIEW OF C++ 1

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

EE 109 Lab 8a Conversion Experience

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

Transcription:

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

Learning Objectives Recursive void Functions Tracing recursive calls Infinite recursion, overflows Recursive Functions that Return a Value Powers function Thinking Recursively Recursive design techniques Binary search 13-2

Introduction to Recursion A function that "calls itself" Said to be recursive In function definition, call to same function C++ allows recursion As do most high-level languages Can be useful programming technique Has limitations 13-3

Recursive void Functions Divide and Conquer Basic design technique Break large task into subtasks Subtasks could be smaller versions of the original task! When they are recursion 13-4

Recursive void Function Example Consider task: Search list for a value Subtask 1: search 1 st half of list Subtask 2: search 2 nd half of list Subtasks are smaller versions of original task! When this occurs, recursive function can be used. Usually results in "elegant" solution 13-5

Recursive void Function: Vertical Numbers Task: display digits of number vertically, one per line Example call: writevertical(1234); Produces output: 1 2 3 4 13-6

Vertical Numbers: Recursive Definition Break problem into two cases Simple/base case: if n<10 Simply write number n to screen Recursive case: if n>=10, two subtasks: 1- Output all digits except last digit 2- Output last digit Example: argument 1234: 1 st subtask displays 1, 2, 3 vertically 2 nd subtask displays 4 13-7

writevertical Function Definition Given previous cases: void writevertical(int n) { } if (n < 10) //Base case cout << n << endl; else { //Recursive step writevertical(n/10); cout << (n%10) << endl; } 13-8

writevertical Trace Example call: writevertical(123); writevertical(12); (123/10) writevertical(1); (12/10) cout << 1 << endl; cout << 2 << endl; cout << 3 << endl; Arrows indicate task function performs Notice 1 st two calls call again (recursive) Last call (1) displays and "ends" 13-9

Recursion A Closer Look Computer tracks recursive calls Stops current function Must know results of new recursive call before proceeding Saves all information needed for current call To be used later Proceeds with evaluation of new recursive call When THAT call is complete, returns to "outer" computation 13-10

Recursion Big Picture Outline of successful recursive function: One or more cases where function accomplishes it s task by: Making one or more recursive calls to solve smaller versions of original task Called "recursive case(s)" One or more cases where function accomplishes it s task without recursive calls Called "base case(s)" or stopping case(s) 13-11

Infinite Recursion Base case MUST eventually be entered If it doesn t infinite recursion Recursive calls never end! Recall writevertical example: Base case happened when down to 1-digit number That s when recursion stopped 13-12

Infinite Recursion Example Consider alternate function definition: void newwritevertical(int n) { newwritevertical(n/10); cout << (n%10) << endl; } Seems "reasonable" enough Missing "base case"! Recursion never stops 13-13

Stacks for Recursion A stack Specialized memory structure Like stack of paper Place new on top Remove when needed from top Called "last-in/first-out" memory structure Recursion uses stacks Each recursive call placed on stack When one completes, last call is removed from stack 13-14

Stack Overflow Size of stack limited Memory is finite Long chain of recursive calls continually adds to stack All are added before base case causes removals If stack attempts to grow beyond limit: Stack overflow error Infinite recursion always causes this 13-15

Recursion Versus Iteration Recursion not always "necessary" Not even allowed in some languages Any task accomplished with recursion can also be done without it Nonrecursive: called iterative, using loops Recursive: Runs slower, uses more storage Elegant solution; less coding 13-16

Recursive Functions that Return a Value Recursion not limited to void functions Can return value of any type Same technique, outline: 1. One+ cases where value returned is computed by recursive calls Should be "smaller" sub-problems 2. One+ cases where value returned computed without recursive calls Base case 13-17

Return a Value Recursion Example: Powers Recall predefined function pow(): result = pow(2.0,3.0); Returns 2 raised to power 3 (8.0) Takes two double arguments Returns double value Let s write recursively For simple example 13-18

Function Definition for power() int power(int x, int n) { if (n<0) { cout << "Illegal argument"; exit(1); } if (n>0) return (power(x, n-1)*x); else return (1); } 13-19

Calling Function power() Example calls: power(2, 0); returns 1 power(2, 1); returns (power(2, 0) * 2); returns 1 Value 1 multiplied by 2 & returned to original call 13-20

Calling Function power() Larger example: power(2,3); power(2,2)*2 power(2,1)*2 power(2,0)*2 1 Reaches base case Recursion stops Values "returned back" up stack 13-21

Tracing Function power(): Display 13.4 Evaluating the Recursive Function Call power(2,3) 13-22

Thinking Recursively Ignore details Forget how stack works Forget the suspended computations Yes, this is an "abstraction" principle! And encapsulation principle! Let computer do "bookkeeping" Programmer just think "big picture" 13-23

Thinking Recursively: power Consider power() again Recursive definition of power: power(x, n) returns: power(x, n 1) * x Just ensure "formula" correct And ensure base case will be met 13-24

Recursive Design Techniques Don t trace entire recursive sequence! Just check 3 properties: 1. No infinite recursion 2. Stopping cases return correct values 3. Recursive cases return correct values 13-25

Recursive Design Check: power() Check power() against 3 properties: 1. No infinite recursion: 2 nd argument decreases by 1 each call Eventually must get to base case of 1 2. Stopping case returns correct value: power(x,0) is base case Returns 1, which is correct for x 0 3. Recursive calls correct: For n>1, power(x,n) returns power(x,n-1)*x Plug in values correct 13-26

Tail recursion A function that is tail recursive if it has the property that no further computation occurs after the recursive call; the function immediately returns. Tail recursive functions can easily be converted to a more efficient iterative solution May be done automatically by your compiler 13-27

Mutual Recursion When two or more functions call each other it is called mutual recursion Example Determine if a string has an even or odd number of 1 s by invoking a function that keeps track if the number of 1 s seen so far is even or odd Would result in stack overflow for long strings 13-28

Mutual Recursion Example (1 of 2) // Recursive program to determine if a string has an even number of 1's. #include <iostream> #include <string> using namespace std; // Function prototypes bool evennumberofones(string s); bool oddnumberofones(string s); // If the recursive calls end here with an empty string // then we had an even number of 1's. bool evennumberofones(string s) { if (s.length() == 0) return true; // Is even else if (s[0]=='1') return oddnumberofones(s.substr(1)); else return evennumberofones(s.substr(1)); } 13-29

Mutual Recursion Example (2 of 2) // if the recursive calls end up here with an empty string // then we had an odd number of 1's. bool oddnumberofones(string s) { if (s.length() == 0) } int main() { return false; // Not even else if (s[0]=='1') return evennumberofones(s.substr(1)); else return oddnumberofones(s.substr(1)); string s = "10011"; } if (evennumberofones(s)) cout << "Even number of ones." << endl; else cout << "Odd number of ones." << endl; return 0; 13-30

Binary Search Recursive function to search array Determines IF item is in list, and if so: Where in list it is Assumes array is sorted Breaks list in half Determines if item in 1 st or 2 nd half Then searches again just that half Recursively (of course)! 13-31

Display 13.6 Pseudocode for Binary Search 13-32

Checking the Recursion Check binary search against criteria: 1. No infinite recursion: Each call increases first or decreases last Eventually first will be greater than last 2. Stopping cases perform correct action: If first > last no elements between them, so key can t be there! IF key == a[mid] correctly found! 3. Recursive calls perform correct action If key < a[mid] key in 1 st half correct call If key > a[mid] key in 2 nd half correct call 13-33

Execution of Binary Search: Display 13.8 Execution of the Function search 13-34

Efficiency of Binary Search Extremely fast Compared with sequential search Half of array eliminated at start! Then a quarter, then 1/8, etc. Essentially eliminate half with each call Example: Array of 100 elements: Binary search never needs more than 7 compares! Logarithmic efficiency (log n) 13-35

Recursive Solutions Notice binary search algorithm actually solves "more general" problem Original goal: design function to search an entire array Our function: allows search of any interval of array By specifying bounds first and last Very common when designing recursive functions 13-36

Summary 1 Reduce problem into smaller instances of same problem -> recursive solution Recursive algorithm has two cases: Base/stopping case Recursive case Ensure no infinite recursion Use criteria to determine recursion correct Three essential properties Typically solves "more general" problem 13-37