CMSC 150 LECTURE 7 RECURSION

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

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.

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

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

Department of Computer Science Yale University Office: 314 Watson Closely related to mathematical induction.

CS 112 Introduction to Programming

26 Feb Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. Greatest Common Divisor. Greatest Common Divisor

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

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

2.3 Recursion 7/21/2014 5:12:34 PM

Recursion LOGO STYLE GUIDE Schools within the University 19

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

Recursion. Chapter 5

Chapter 15: Recursion

Lecture P6: Recursion

Reduction & Recursion Overview

Chapter 10: Recursive Problem Solving

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

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

Lecture 24 Tao Wang 1

CSE 214 Computer Science II Recursion

Recursion. notes Chapter 8

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

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

Loops / Repetition Statements

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

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

Recursive Definitions

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

1.7 Recursion. Department of CSE

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

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

CS 112 Introduction to Programming

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

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

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

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

Recursion. Chapter 17 CMPE13. Cyrus Bazeghi

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

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

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

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

CmpSci 187: Programming with Data Structures Spring 2015

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

Recursion CS GMU

Recursive Problem Solving

CSC 222: Computer Programming II. Spring 2005

Recursion. CSCI 112: Programming in C

Recursion. Fundamentals of Computer Science

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

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

CS/CE 2336 Computer Science II

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

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

EE 368. Weeks 4 (Notes)

Introduction to the Java Basics: Control Flow Statements

CSC 222: Object-Oriented Programming. Spring 2012

Decision-Making and Repetition

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

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

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

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

CS200: Recursion and induction (recap from cs161)

ESC101 : Fundamental of Computing

CS 112 Introduction to Programming

Reading 8 : Recursion

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

Recursion. Chapter 7

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

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

Recursive Functions. Biostatistics 615 Lecture 5

1.3 Conditionals and Loops

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

CS 3410 Ch 7 Recursion

CSE 143 Lecture 11. Decimal Numbers

Combinatorial Search. permutations backtracking counting subsets paths in a graph. Overview

Programming with Recursion. What Is Recursion?

You should know the first sum above. The rest will be given if you ever need them. However, you should remember that,, and.

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

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

recursive algorithms 1

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

CT 229 Methods Continued

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

Chapter 13 Recursion. Chapter Objectives

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

Chapter 17 Recursion

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

Algorithm Analysis and Design

COMPUTER SCIENCE. Computer Science. 6. Recursion. Computer Science. An Interdisciplinary Approach. Section 2.3.

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

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

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

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

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

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

SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Controls Structure for Repetition

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

Transcription:

CMSC 150 INTRODUCTION TO COMPUTING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH INTRODUCTION TO PROGRAMMING IN JAVA: AN INTERDISCIPLINARY APPROACH, SEDGEWICK AND WAYNE (PEARSON ADDISON-WESLEY 2007) LECTURE 7 RECURSION

OVERVIEW Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations are naturally self-referential. A folder containing files and other folders. Mathematical sequences - f n+1 = f n + 1 (whole numbers) Exploring mazes make a step in the maze, then keep exploring the maze

EXAMPLE COUNTING Lets take an example of counting from 0 The next number is the previous number plus 1, or mathematically: f n = f n 1 + 1, where f 0 = 0 So lets compute f 5 f 5 = f 4 + 1, this would be great if we knew f 4, so lets expand it f 5 = f 3 + 1 + 1, then f 5 = f 2 + 1 + 1 + 1, then f 5 = f 5 = f 1 + 1 + 1 + 1 + 1, then f 0 + 1 + 1 + 1 + 1 + 1, then finally f 5 = 0 + 1 + 1 + 1 + 1 + 1 = 5

PRACTICE RECURSIVE FORMULAS FIBONACCI SEQUENCE The Fibonacci Sequence is used in various places in mathematics and computer science f n = f n 1 + f n 2, where f 0 = 0, f 1 = 1 Expand and evaluate f 6, work with a partner and show your work

HOW DO WE DO RECURSION IN CODE? Simply call the function within its own body public static void foo() { //possibly do some stuff foo(); //This example of recursion //prossibly do some more stuff

EXAMPLE COUNTING //This function counts using recursion public static int recursivecount(int n) { //f 0 = 0 if(n == 0) return 0; //f n = f n 1 + 1 return recursivecount(n-1) + 1; Together lets trace System.out.println(recursiveCount(3)); recursivecount(3) return recursivecount(2) + 1 return recursivecount(1) + 1; return recursivecount(0) + 1; return 0; return 0 + 1; return 1 + 1; return 2 + 1; 3

PRACTICE RECURSIVE CODE FIBONACCI SEQUENCE Write a Java function Fibonacci for f n = f n 1 + f n 2 public static int Fibonacci(int n) { if(n == 0) return 0; if(n == 1) return 1; return Fibonacci(n-1) + Fibonacci(n-2); Practice tracing Fibonacci(3) Fibonacci(3) return Fibonacci(2) + Fibonacci(1); return Fibonacci(1) + Fibonacci(0); return 1; return 1 + Fibonacci(0); return 0; return 1 + 0; return 1 + Fibonacci(1); return 1; return 1 + 1; 2

DESIGNING RECURSIVE FUNCTIONS Identify the base case The base case is the part of the recursion not defined in terms of itself, e.g., f 0 = 0, f 1 = 1 This is when the recursion stops! If you forget your base case, then the world will end Really an infinite series of function calls until your computer crashes (if it ever does) Identify the recursive process This is the algorithmic process or algorithmic formula Write the code

PRACTICE DESIGNING RECURSIVE FUNCTIONS GREATEST COMMON DENOMINATOR (GCD) We saw this in homework For two integers p and q, if q divides p then the GCD of p and q is y Otherwise the GCD of p and q is the same as q and p%q Step 1: Identify the base case q = 0 implies that the GCD is p Step 2: Identify the recursive step GCD(q, p%q) Step 3: Code public static int GCD(int p, int q) { if(q == 0) return p; return GCD(q, p%q);

RECURSIVE GCD DEMO 1. public class Euclid { 2. public 3. 4. 5. 6. 7. public static void main(string[] args) { 8. int p = Integer.parseInt(args[0]); 9. int q = Integer.parseInt(args[1]); 10. System.out.println(gcd(p, q)); 11. 12.

p = 1272, q = 216 gcd(1272, 216)

p = 1272, q = 216 gcd(1272, 216)

p = 1272, q = 216 gcd(1272, 216)

1272 = 216 5 + 192 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192)

p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192)

p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192)

p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24)

p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24)

p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24)

p = 24, q = 0 p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24) gcd(24, 0)

p = 24, q = 0 p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24) gcd(24, 0)

p = 24, q = 0 p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24) 24 gcd(24, 0)

p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) gcd(192, 24) 24

p = 192, q = 24 p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) 24 gcd(192, 24) 24

p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) gcd(216, 192) 24

p = 216, q = 192 p = 1272, q = 216 gcd(1272, 216) 24 gcd(216, 192) 24

p = 1272, q = 216 gcd(1272, 216) 24

p = 1272, q = 216 gcd(1272, 216) 24 public class Euclid { public public static void main(string[] args) { int p = Integer.parseInt(args[0]); int q = Integer.parseInt(args[1]); 24 System.out.println(gcd(p, q)); 24 % java Euclid 1272 216 24

TOWERS OF HANOI http://en.wikipedia.org/wiki/image:hanoiklein.jpg

PRACTICE TOWERS OF HANOI Design recursive algorithm to move all the discs from the leftmost peg to the rightmost one. Only one disc may be moved at a time. A disc can be placed either on empty peg or on top of a larger disc. start finish

SOLUTION TOWERS OF HANOI Move n-1 smallest discs right. Move largest disc left. Move n-1 smallest discs right.

CODE TOWERS OF HANOI 1. public class TowersOfHanoi { 2. public static void moves(int n, boolean left) { if (n == 0) return; 3. moves(n-1,!left); 4. if (left) System.out.println(n + " left"); 5. else System.out.println(n + " right"); 6. moves(n-1,!left); 7. 8. 9. public static void main(string[] args) { 10. int N = Integer.parseInt(args[0]); 11. moves(n, true); 12. 13. % java TowersOfHanoi 3 1 left 2 right 1 left 3 left 1 left 2 right 1 left

RECURSION TREE (FUNCTION TRACE) TOWERS OF HANOI 3, true 1 14 15 28 2, false 2, false 2 7 8 13 16 21 22 27 1, true 1, true 1, true 1, true 3 4 5 6 9 10 11 12 17 18 19 20 23 24 25 26 1 left 2 right 1 left 3 left 1 left 2 right 1 left

DOWNSIDE OF RECURSION F(50) Recursion is not always efficient! Take for instance, the Fibonacci sequence F(49) F(48) F(47) F(47) F(46) F(46) F(45) F(48) F(47) F(46) F(46) F(45) F(45) F(44) recursion tree for naïve Fibonacci function public static long F(int n) { if (n == 0) return 0; if (n == 1) return 1; return F(n-1) + F(n-2); F(50) is called once. F(49) is called once. F(48) is called 2 times. F(47) is called 3 times.... F(1) is called 12,586,269,025 times.

BEST PRACTICE CONVERT RECURSIVE ALGORITHMS TO ITERATIVE ONES Try to do this whenever possible Example Fibonacci Sequence 1. //This is an example conversion. You can be even more efficient! 2. public static long F(int n) { 3. if (n == 0) return 0; 4. long[] F = new long[n+1]; //Allows reuse of computed values 5. F[0] = 0; 6. F[1] = 1; 7. for (int i = 2; i <= n; i++) // Iterative means repetition until failure condition, // typically done with loops and not recursion 8. F[i] = F[i-1] + F[i-2]; 9. return F[n]; 10.

SUMMARY How to write simple recursive programs? Base case, reduction step. Trace the execution of a recursive program. Why learn recursion? New mode of thinking. Powerful programming tool