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

Similar documents
CMSC 150 LECTURE 7 RECURSION

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

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

C22a: Problem Solving using Recursion

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

CS/CE 2336 Computer Science II

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Module 05: Types of recursion

Chapter 18 Recursion. Motivations

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

CS 310 Advanced Data Structures and Algorithms

RECURSION. Many Slides from Ken Birman, Cornell University

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

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

Building Java Programs

Lecture 6 CS2110 Spring 2013 RECURSION

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

CS 3410 Ch 7 Recursion

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

CS116 - Module 5 - Accumulative Recursion

CIS265 - Spring Exam 2 First Name Last Name CSU#

Reduction & Recursion Overview

Recursive Definitions

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

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

CS1 Lecture 15 Feb. 18, 2019

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

Recursive definition: A definition that is defined in terms of itself. Recursive method: a method that calls itself (directly or indirectly).

CS1 Lecture 15 Feb. 19, 2018

Recursion. Recursion [Bono] 1

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

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

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

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

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

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

Chapter 15: Recursion

Anatomy of a static method, S&W, 2.1, figure page 188. Class.name or just name Scope, S&W, 2.1, figure page 189. Overloading

Chapter 10: Recursive Problem Solving

CS 161 Intro to CS I. Finish Pointers/Start Recursion

CSE 143 Lecture 10. Recursive Programming. reading: slides adapted from Marty Stepp and Hélène Martin

Koch snowflake. Fractal Fern

Recursion. Chapter 5

Lecture 10: Recursive Functions. Computer System and programming in C 1

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

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

Divide-and-Conquer. Divide-and conquer is a general algorithm design paradigm:

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

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

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

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

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

Lecture 10: Recursion vs Iteration

Types of Recursive Methods

Recursion CS GMU

Lecture 7 CS2110 Fall 2014 RECURSION

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:


Recursion. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function A from within function A!

CSE 230 Intermediate Programming in C and C++ Recursion

Inductive Definition to Recursive Function

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

Lecture 6: Recursion RECURSION

Chapter 4 Functions By C.K. Liang

Complexity of Algorithms

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

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

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

1.7 Recursion. Department of CSE

More Complicated Recursion CMPSC 122

t 1 =2 t n =3t n 1 1,n 1

Recursion. CSCI 112: Programming in C

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

CSE 143 Lecture 11. Decimal Numbers

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

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

Programming II (CS300)

IUSE Knowledge Test. 1. Demographic Questions. IUSE Knowledge Test. 2. Computational Thinking Knowledge Test

Iteration vs Recursion in Introduction to Programming Classes: An Empirical Study

recursive algorithms 1

CS 106X, Lecture 7 Introduction to Recursion

RECURSION. Problem Solving with Computers-II 6

CS 112 Introduction to Programming

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution

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

Decision-Making and Repetition

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

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

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

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

Advanced Computer Programming

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

Programming II (CS300)

Object-Oriented Programming and Design D0010E. Interactive lecture 2. Overview of the lecture. Writing larger classes Documentation Recursion

JAVA PROGRAMMING LAB. ABSTRACT EXTRA LAB, In this Lab you will learn working with recursion, JRX, Java documentations

CSE 143. Computer Programming II

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

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

Transcription:

CH. 5 RECURSION ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016)

OVERVIEW Recursion is an algorithmic technique where a function calls itself directly or indirectly. Can also involve data ownership Why learn recursion? Powerful algorithmic 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

EXERCISE 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 Pseudocode Algorithm Foo 1. {Possibly do some stuff} Java 1. public static void foo() { 2. //possibly do some stuff 3. foo(); //This example of recursion 4. //prossibly do some more stuff 5. } 2. Foo() 3. {Possibly do some more stuff}

EXAMPLE COUNTING //This function counts using recursion Algorithm recursivecount Input: Integer n Output: The nth integer 1. {f 0 = 0} 2. if n = 0 then 3. return 0 4. {f n = f n 1 + 1} 5. return recursivecount(n 1)+ 1 Together lets trace recursivecount(3);

EXERCISE FIBONACCI SEQUENCE Write an algorithm that computes the nth Fibonacci number: Practice tracing Fibonacci(4) f n = f n 1 + f n 2

CHARACTERISTICS OF RECURSION All recursive methods have the following characteristics: One or more base cases (the simplest case) are used to stop recursion. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. In general, to solve a problem using recursion, you break it into subproblems. If a subproblem resembles the original problem, you can apply the same approach to solve the subproblem recursively. This subproblem is almost the same as the original problem in nature with a smaller size.

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

EXAMPLE GREATEST COMMON DENOMINATOR (GCD) GCD For two integers p and q, if q divides p then the GCD of p and q is q Otherwise the GCD of p and q is the same as q and p mod q Step 2: Identify the recursive step GCD(q, p mod q) Step 3: Write algorithm/code Step 1: Identify the base case q = 0 implies that the GCD is p

EXAMPLE GREATEST COMMON DENOMINATOR (GCD) Algorithm gcd Input: Integers p and q Output: Greatest common denominator of p and q 1.if q = 0 then 2. return p; 3.return gcd(q, p mod q); 4.// Lets trace together gcd(1272, 216)

RECURSIVE HELPER METHODS Many problems can be solved with recursion, as it is loosely a looping technique. Example: palindrome However this example has an inefficiency, what is it? Algorithm ispalindrome Input: String s Output: true if s is a palindrome, false otherwise 1. if s.length() 1 then 2. return true; 3. else if s.charat(0) s.charat(s.length() - 1) then 4. return false; 5. else 6. return ispalindrome(s.substring(1, s.length() - 1));

RECURSIVE HELPER METHODS The preceding recursive ispalindrome method is not efficient, because it creates a new string for every recursive call. To avoid creating new strings, use a non-recursive method to jump start the recursive process, often with additional parameters Algorithm ispalindrome Input: String s Output: true if s is a palindrome, false otherwise 1. return ispalindrome(s, 0, s.length() - 1); Algorithm ispalindrome Input: String s, Integers low and high Output: true if s is a palindrome, false otherwise 1. if high low then 2. return true; 3. else if s.charat(low) s.charat(high) then 4. return false; 5. else 6. return ispalindrome(s, low + 1, high - 1);

ANALYZING RECURSIVE METHODS Concerning time Count the total number of operations based on the initial recursive invocation, e.g., the non-recursive method Includes all operations of invocations down to the base case Palindrome() takes O(n) time because each character of the string is read once. Concerning memory Yes, big-oh captures memory. The parameters of each invocation need a separate place in memory So, k invoations at the very least takes O k extra memory for the space of the method invocation. Tally up all memory of all invocations to see the correct answer The first ispalindrome() took O n 2 memory because substrings were copied, we needed more memory. So i 0 n 1 n 2i O n 2 The second ispalindrome() took O n memory because only primitive types were copied to each invocation.

EXERCISE With your team, write and analyze a recursive algorithm that determines the number of uppercase letters in a string. Use a non-recursive helper to make an efficient algorithm Analyze time complexity Analyze memory complexity

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) Algorithm fib Input: Integer n Output: nth Fibonacci number 1. if n = 0 then 2. return 0 3. if n = 1 then 4. return 1 5. return fib(n 1) + fib(n 2) recursion tree for naïve Fibonacci function fib(50) is called once. fib(49) is called once. fib(48) is called 2 times. fib(47) is called 3 times.... fib(1) is called 12,586,269,025 times.

BEST PRACTICE Try to Convert Recursive Algorithms to iterative ones whenever possible Example Fibonacci Sequence in Java 1. //This is an example conversion. You can be even more efficient! 2. public static long fib(int n) { 3. if (n == 0) return 0; 4. if (n == 1) return 1; 5. int fn2 = 0; 6. int fn1 = 1; 7. int fn = 1; 8. // Iterative means repetition until failure condition, 9. // typically done with loops and not recursion 10. for (int i = 2; i < n; i++) { 11. fn = fn1 + fn2; 12. fn2 = fn1; 13. fn1 = fn; 14. } 15. return fn; 16. }

OR DO TAIL RECURSION Tail recursion is when the last operation of a function is the recursive call The compiler can optimize this to safe memory by reusing the space of the previous method invocation this can only be done on tail recursion Example with factorial: f n = n f n 1 Without tail recursion With tail recusion 1. public static long factorial(int n) { 2. return factorial(n, 1); 3. } 4. public static long factorial( int n, int result) { 5. if(n == 0) return result; 6. return factorial(n 1, n * result); 7. } 1. public static long factorial(int n) { 2. if(n == 0) return 1; 3. return n*factorial(n-1); 4. }

SUMMARY How to write recursive processes? Base case and reduction step. Why learn recursion? New mode of thinking. Powerful algorithmic tool