Recursion. Chapter 5

Similar documents
Recursion. Chapter 7

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

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

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

CMSC 150 LECTURE 7 RECURSION

Chapter 15: Recursion

Reduction & Recursion Overview

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

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

Recursive Definitions

EE 368. Weeks 4 (Notes)

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

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Recursion. Based on Chapter 7 of Koffmann and Wolfgang. Chapter 7: Recursion 1

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

Programming with Recursion. What Is Recursion?

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

Reading 8 : Recursion

Lecture 8 Recursion. The Mirrors

CS 310 Advanced Data Structures and Algorithms

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

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

recursive algorithms 1

Mathematical Induction

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

Chapter 17 Recursion

Chapter 10: Recursive Problem Solving

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

CS 3410 Ch 7 Recursion

Solutions to the Second Midterm Exam

Recursion. Chapter 17 CMPE13. Cyrus Bazeghi

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

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

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

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

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

Recursive Functions. Biostatistics 615 Lecture 5

Recursive Problem Solving

CSE 214 Computer Science II Recursion

Lecture 24 Tao Wang 1

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

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

Recursion Chapter 3.5

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

CS/CE 2336 Computer Science II

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

csci 210: Data Structures Recursion

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

2.3 Recursion 7/23/2015 3:06:35 PM

Recursion vs Induction

Lecture P6: Recursion

15. Pointers, Algorithms, Iterators and Containers II

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

CSC 273 Data Structures

! New mode of thinking. ! Powerful programming paradigm. ! Mergesort, FFT, gcd. ! Linked data structures.

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

What is Recursion? Chapter 17 Recursion. Executing RunningSum. High-Level Example: Binary Search

Recursion. CSE 2320 Algorithms and Data Structures University of Texas at Arlington

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

11. Recursion. n (n 1)!, otherwise. Mathematical Recursion. Recursion in Java: Infinite Recursion. 1, if n 1. n! =

Chapter 19 Recursion and Method Redefinition

12. Recursion. n (n 1)!, otherwise. Educational Objectives. Mathematical Recursion. Recursion in Java: 1, if n 1. n! =

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

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

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

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

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

Chapter 10 Recursion. by Jeri R. Hanly and Elliot B. Koffman Pei-yih Ting. -- L. Peter Deutsch

Recursion vs Induction. CS3330: Algorithms The University of Iowa

COMP 250 Fall Recursive algorithms 1 Oct. 2, 2017

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

Programming II (CS300)

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

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

Odds and Ends. Think about doing research Programming grading. Assignment 3 due Tuesday

Solving problems by recursion

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

Programming II (CS300)

1.7 Recursion. Department of CSE

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

DEEPIKA KAMBOJ UNIT 2. What is Stack?

CSC 222: Object-Oriented Programming. Spring 2012

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


Programming II (CS300)

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

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

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

CS200: Recursion and induction (recap from cs161)

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

Recursion. Fundamentals of Computer Science

Summer Final Exam Review Session August 5, 2009

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

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

Recursion. Example R1

Analyzing Complexity of Lists

Lecture 10: Recursion vs Iteration

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

cs Java: lecture #6

Transcription:

Recursion Chapter 5

Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn about recursive data structures and recursive methods for a LinkedList class To understand how to use recursion to solve the Towers of Hanoi problem Chapter 7: Recursion 2

Chapter Objectives (continued) To understand how to use recursion to process twodimensional images To learn how to apply backtracking to solve search problems such as finding a path through a maze Chapter 7: Recursion 3

Recursion Recursion is a problem-solving approach in which a problem is solved using repeatedly applying the same solution to smaller instances. Each instance to the problem has size. An instance of size n can be solved by putting together solutions of instances of size at most n-1. An instance of size 1 or 0 can be solved very easily. Chapter 7: Recursion 4

An Example: Computing the Length of a List Object Two data fields: data and next. If the element is null, return 0. If the element is not null, but the next is null, return 1. Otherwise, return 1 + the length of the list starting with the next. public int count() { if (this == null) return 0; // Base case 0 else if (next == null) return 1; // Base case 1 else return 1 + next.count(); // Recursive call } Chapter 7: Recursion 5

Proof of Correctness is Similar to Proof-By- Induction Proof by induction Prove the statement is true for the base case (size 0,1, or whatever). Show that if the statement is assumed true for n, then it must be true for n+1. Chapter 7: Recursion 6

Proof of Correctness Recursive proof is similar to induction. Verify that: The base case is recognized and solved correctly Each recursive case makes progress towards the base case If all smaller problems are solved correctly, then the original problem is also solved correctly Chapter 7: Recursion 7

System Processing of a Recursive Call Push onto a stack the information of the current execution. Execute the recursive call. Retrieve the information from the stack by pop. Too many recursive calls without pop will result in stack overflow. Chapter 7: Recursion 8

Recursively Defined Mathematical Functions Chapter 7: Recursion 9

Recursive Definitions of Mathematical Formulas Factorial: n! where n >= 0. 0! = 1. If n > 0, n! = n (n-1)!. Powers: x n, x to the power of n, where x > 0, n >= 0. If n=0, x n = 1. If n>0, x n = x x n-1. Greatest Common Divisor: gcd(a,b), a, b >= 0 gcd(a,b) = gcd(b,a). If b=0, gcd(a,b) = a. If a >= b, gcd(a,b) = gcd(a-b,b). Chapter 7: Recursion 10

Factorial, Powers, and gcd public static int factorial(int n) { if (n<0) return 0; else if (n=0) return 1; else return n * factorial(n-1); } public static int powers(int x, int n) { if ((x <= 0) (n < 0)) return 0; else if (n == 0) return 1; else return n * powers(x, n-1); } public static int gcd(int a, int b) { if ((a<0) (b<0)) return 0; else if (a == 0) return b; else if (b == 0) return a; else if (a < b) return gcd(b,a); else return gcd(b, a % b); } Chapter 7: Recursion 11

Recursion Versus Iteration There are similarities between recursion and iteration In iteration, a loop repetition condition determines whether to repeat the loop body or exit from the loop In recursion, the condition usually tests for a base case An iterative solution exists to a problem that is solvable by recursion Recursive code may be simpler than an iterative algorithm and thus easier to write, read, and debug Chapter 7: Recursion 12

Iterative Solutions public static int factorial(int n) { if (n<0) return 0; fac = 1; for (int i=0; i<n; i++) { fac *= i; } return fac; } public static int powers(int x, int n) { if ((x <= 0) (n < 0)) return 0; else if (n == 0) return 1; pow = 1; for (int i=0; i<n; i++) { pow *= x; } return pow; } public static int gcd(int a, int b) { if ((a<0) (b<0)) return 0; if (a < b) { c = a; a = b; b = c; // swap a and b. while (b>0) { r = a % b; a = b; b = r; // Reduce a&b to b&(a mod b). } return a; } Chapter 7: Recursion 13

Efficiency of Recursion Recursive methods are often than iterative methods because the stack overhead is larger than the loop overhead. Recursive methods are easier to write and conceptualize. Chapter 7: Recursion 14

Fibonacci Number F(1) = 1. F(2) = 1. For n>=3, F(n) = F(n-1) + F(n-2) Chapter 7: Recursion 15

An O(2 n ) Recursive Method public static int fibonacci(int n) { if (n <= 2) return 1; else return fibonacci(n-1) + fibonacci(n 2); } Chapter 7: Recursion 16

An O(n) Recursive Method fibo(a,b,c) is invoked to compute F(c+m) when F(m+1) =a and F(m)=b public static int fibo(int fibocurrent, int fiboprevious, int c) { if (c == 1) return fibocurrent; else return fibo(fiboprevious+fibocurrent, fibocurrent, c-1); } Invoke fibo(1,0,n) Chapter 7: Recursion 17

Efficiency of Recursion: Exponential Fibonacci Inefficient Chapter 7: Recursion 18

Efficiency of Recursion: O(n) Fibonacci Chapter 7: Recursion 19

Recursive Array Search Linear Search Versus Binary Search Chapter 7: Recursion 20

Linear Search in an Array A of size S To search A for an element E, invoke the search in the range [0, S-1]. To search in the range [I, S-1] If I == S, then stop the element is not in the array. If the I-th element in the array is the one, stop there. Otherwise, recursively search in the range[i+1,s-1]. Search requires O(S) time. Chapter 7: Recursion 21

Binary Search in a Sorted Array The sorted elements in an array A. The first element is the smallest and the last element is the largest. Maintain the range of indices [I,J] for search. Loop: Indicate Not found if I>J. Let K be the middle index; the integer part of (I+J)/2. If (A[K] == target), indicate Found. Else if (A[K] > target), set J to K-1. Else set I to K+1. At each iteration, the size of range becomes at most a half, so the running time is O(log 2 n). Chapter 7: Recursion 22

Design of a Binary Search Algorithm (continued) Chapter 7: Recursion 23

Algorithm for Binary Search /** search items for target in the range [first, last] * returns the index of the target if found; -1 o.w. */ public int binarysearch(object[] items, Comparable target, int first, int last) { if (first>last) return -1; int mid = (first + last)/2; if (target.compareto(items[mid])==0) { return mid; } else if (target.compareto(items[mid]) < 0) { } return binarysearch(items, target, first, mid-1); } else { return binarysearch(items, target, mid+1, last); } } The target has to be of a data type that implements compareto: CompareTo is a method that gives as an integer the ordering between two elements (usually -1, 0, 1). Chapter 7: Recursion 24

Method Arrays.binarySearch Java API class Arrays contains a binarysearch method Can be called with sorted arrays of primitive types or with sorted arrays of objects If the objects in the array are not mutually comparable or if the array is not sorted, the results are undefined If there are multiple copies of the target value in the array, there is no guarantee which one will be found Throws ClassCastException if the target is not comparable to the array elements Chapter 7: Recursion 25

The Tower Of Hanoi Chapter 7: Recursion 26

Towers of Hanoi There are 64 discs of all distinct diameters slid onto a peg in the increasing order of diameters with the smallest one on the very top. There are two other pegs Move all the discs to one of the two other pegs with the following rules: A disc can be moved only one at a time. A larger disc must not be placed on a smaller disc. Goal: Compute the shortest moves to accomplish this talk. Chapter 7: Recursion 27

Formulation of the Towers-of-Hanoi Problem Consider the sub-problem of moving the top N discs from peg X to peg Y, where 1 <= N <= 64, X Y, and X and Y are members of { L, M, R }. The initial invocation: N = 64, X=L, Y=R/M. Chapter 7: Recursion 28

Algorithm for Towers of Hanoi: N=4 Chapter 7: Recursion 29

Recursive Algorithm for Towers of Hanoi Input N, X, Y N=1: Move the top disc of peg X to peg Y. N>1: Let Z be the peg other than X or Y. Move the top N-1 discs from X to Z. Move the top 1 disc from X to Y. Move the top N-1 discs from Z to Y. Chapter 7: Recursion 30

Towers of Hanoi Class public class TowersOfHanoi { /** Recursive method for Towers of Hanoi pre: the three chars are all distinct @param n is the number of disks @param startpeg is the peg where the disks currently are @param destpeg is the peg which the disks should move to @param temppeg is the remaining peg public static String showmoves(int n, char startpeg, char destpeg, char temppeg) { if (n==1) { return Move disc 1 from + startpeg + to + destpeg + \n ; } else { return TowersOfHanoi(n-1, startpeg, temppeg, destpeg) + Move disc + n + from + startpeg + to + destpeg + \n ; TowersOfHanoi(n-1, temppeg, destpeg, startpeg); } } } Chapter 7: Recursion 31

Backtracking Chapter 7: Recursion 32

Backtracking Backtracking is an approach to implementing systematic trial and error in a search for a solution. It explores alternative search paths and eliminates them if they don t work. It remembers the search history to avoid trying the same path again. Recursion is a natural way to implement backtracking The trace of successive recursive calls represents the search history with an instrumentation of exhaustive search at each level. Chapter 7: Recursion 33

Maze Threading Input: a two-dimensional of cells, M by N BACKGROUND a cell can be walked in BLOCKED a cell that can never be walked in Output: A path from (0,0) to (M-1, N-1) that visits only BACKGROUND cells, if one exists Additional Types: PATH a cell that is determined to be on the path to be built TEMPORARY a non-blocked cell that is found not be on any path to the goal Chapter 7: Recursion 34

Algorithm for Maze Threading Use recursive search from cell (I,J) if (I<0 J<0 I>=M J>=N) { return false; } else if (type of cell (I,J)!= BACKGROUND) { return false; } else { set type of cell (I,J) to PATH; if (I,J) is goal { return true; } else if Search from (I-1,J) returns true { return true; } else if Search from (I+1,J) returns true { return true; } else if Search from (I,J-1) returns true { return true; } else if Search from (I,J+1) returns true { return true; } else { set type of cell (I,J) to TEMPORARY; return false; } } Chapter 7: Recursion 35

Chapter 7: Recursion 36