Data Structures with Java © Rick Mercer

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Unit 181 Recursion Definition Recursive Methods Constructing Recursion Benefits and Usage Infinite Recursion Recursion Removal Examples Exercises.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Lecture 10 Recursion CSE225: Data Structures. 2 A Look Back at Functions #include double distance(double x1, double y1, double x2, double y2) { double.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
1Recursion. 2 Outline thinking recursively recursive algorithms iteration vs. recursion recursive functions integer exponentiation (pow) infinite recursion.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Chapter 17 Recursion Data Structures with Java © Rick Mercer Data Structures with Java © Rick Mercer.
Using Recursion to Convert Number to Other Number Bases Data Structures in Java with JUnit ©Rick Mercer.
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion Powerful Tool
Programming with Recursion
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion Version 1.0.
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Recursion Topic 5.
Topic 6 Recursion.
Recursion what is it? how to build recursive algorithms
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Recursion: The Mirrors
Recursion Chapter 12.
Chapter 15 Recursion.
To understand recursion, you have to understand recursion!
Programming with Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion Recursive Thinking Recursive Programming
Chapter 12 Recursion (methods calling themselves)
Basics of Recursion Programming with Recursion
Java Programming: Chapter 9: Recursion Second Edition
CSC 143 Recursion.
Yan Shi CS/SE 2630 Lecture Notes
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Chapter 18 Recursion.
Chapter 17 Recursion.
Presentation transcript:

Data Structures with Java © Rick Mercer Chapter 17 Recursion

Recursion Outline Consider some recursive solutions to non-computer problems Compare iterative and recursive solutions Identify the recursive case and the base cases in some simple recursive algorithms Implement recursive methods (methods that call themselves) 3

Recursion Recursion can describe everyday examples Show everything in a folder and all it subfolders show everything in top folder show everything in each subfolder in the same manner How to look up a word in a dictionary look up a word (use alphabetical ordering) or look up word to define the word you are looking up A queue is empty or has someone at the front of the queue followed by a queue. Can we have a waiting line with 1 element?

Recursive definition: Arithmetic Expression Arithmetic expression is defined as a numeric constant an numeric identifier an arithmetic expression enclosed in parentheses 2 arithmetic expressions with a binary operator like + - / or * Note: The term arithmetic expression is defined with the term arithmetic expression but the first two bullets do not

Mathematical Examples Consider the factorial method (0!=1) The recursive definition: What is f(2)? ___________ What is f(3)? ___________

Recursive and non-recursive solutions // Non-recursive solution, using a loop // precondition: n >= 0 public long factRep(int n) { long result = 1; for(int j = 2; j <= n; j++) result = j * result; return result; } // Recursive solution public long factRec(int n) { if(n == 0) return 1; // base case else return n * factRec(n - 1); // Recursive case } // Don't call factRec(n + 1)! @Test public void testFacortialMethods() { assertEquals(1, factRep(0)); assertEquals(1, factRec(0)); assertEquals(1, factRep(1)); assertEquals(1, factRec(1)); assertEquals(2, factRep(2)); assertEquals(2, factRec(2)); assertEquals(6, factRep(3)); assertEquals(6, factRec(3)); assertEquals(24, factRep(4)); assertEquals(24, factRec(4)); assertEquals(3628800, factRep(10)); assertEquals(3628800, factRec(10)); }

Trace factRec(4) Method calls itself until base case is reached

How Recursion works Method calls generate activation records Depending on the system, the activation record might store all parameter values and local values return point -- where to go after the method finishes imagine all this is in a box the data is stored in an activation frame (a box) and pushed onto a stack -- one on top of the other when the method finishes, the activation frame stack is popped it disappears, control returns to where it was called

A method that calls itself public void forward(int n){ if(n > 1) forward(n - 1); // recursive call: n goes toward 0 // RP# FORWARD System.out.print(n); } @Test public void showRecursion(){ int arg = 3; forward(arg); // RP# SHOW arg = 999; RP# FORWARD n 1 RP# FORWARD n 2 RP# FORWARD n 2 RP# SHOW n 3 RP# SHOW n 3 RP# MAIN n 3 arg 3 arg 3 arg 3 start in showR arg 3

The base case is reached Several activation frames are stacked When parameter (n) == 1, there is no recursive call. (1) execute the base case when n == 1 System.out.print(n); The output is 1 and the method is done (1) RP# FORWARD n 1 RP# FORWARD n 2 public void forward(int n){ if(n > 1) forward(n - 1); // recursive call // RP# FORWARD System.out.print(n); } RP# SHOW n 3 arg 3

Returning back to SHOW (2) Return to previous call and pop box on top continue from RP# FORWARD, print 2 (3) Return to previous call and pop box on top continue from RP# FORWARD, print 3 (4) Return to showRecursion, pop box on top execute arg = 999 (to indicate we're back in SHOW) The SHOW method is done, Output is 123 (2) RP# FORWARD n 2 (3) RP# SHOW n 3 RP# SHOW n 3 (4) arg 3 Back in showR arg 3 999 arg 3

Write gcd(int a, int b) recursively GCD Return the greatest common divisor of two positive integers iteratively and recursively public int GCDwithALoop(int a, int b) { while (b != 0) { int temp = a; a = b; b = temp % b; } return a; Write gcd(int a, int b) recursively

Infinite Recursion A recursive method will keep calling itself until the base case is reached there must be at least one base case this could be to do nothing each call should make progress towards a base case call a simpler version could be a smaller or larger argument than the parameter could be a smaller portion of an array or linked structure How many method calls are in the next code?

Infinite Recursion assertEquals(2, (factRec(2)); // Stopped when n == 1024 on one machine public long factRec(int n) { System.out.println(n); if(n == 0) return 1; // base case else return n * factRec(n + 1); } java.lang.StackOverflowError

Determine the base and recursive cases When writing recursive methods Make sure there is at least one base case at least one situation where a recursive call is not made. There could be more than one base case The method might return a value, or do nothing at all There could be one or more recursive cases a recursive call must be a simpler version of the same problem the recursive call should bring the method closer to the base case perhaps pass n-1 rather than n.

Palindrome Palindrome is a String that equals itself when reversed: "racecar" "abba" "12321" Write a recursive method that returns true if a given string is a palindrome What is/are the base case(s)? What is the recursive case? @Test public void testIsPalindrome() { assertTrue(isPalindrome("A")); assertTrue(isPalindrome("racecar")); assertTrue(isPalindrome("amanaplanacanalpanama")); assertTrue(isPalindrome("madamimadam")); assertFalse(isPalindrome("not")); assertFalse(isPalindrome("Aba")); assertFalse(isPalindrome("1231")); assertFalse(isPalindrome("1233 21")); }

Recursion = Recursion( Again-1 ); A Combinatorial method This example of a recursive solution comes from the field of Combinatorics Problem: A D.J. plays 10 songs each hour. There are 40 different songs. How many different one hour sets are possible? Or in general given 40 different things, how many sets of size 10 can be chosen Or using the standard notation – n choose k

Recursive n choose k (con.) In any given hour, we could play "Stairway" All the possible sets are those that have "Stairway"and those that don't ( sum below) After picking this one song--now a simpler problem--the DJ must pick 9 more from the remaining 39 songs (from 39 choose 9) Possible sets are those with "Stairway", and those without

From 5 choose 2 All the sets with A (from 4 choose 1): Here is simpler problem, from 5 letters choose 2 A B C D E All the sets with A (from 4 choose 1): AB AC AD AE Those without A (from 4 choose 2, no A): BC BD BE CD CE DE

Recursive n choose k (con.) Or, in general, we get Rewritten as a method named c that has two parameters n and k: We're getting closer but where is the base case?

The base cases for n choose k First, n must be at least as big as k: We cannot choose a 10 song set from 9 songs When n == k, there is only one choice only one possible 10 song set from 10 songs To be meaningful, k must be at least 1 We're not interested in sets with 0 songs When k is 1, there are n ways to choose If we only play 1 song sets, and we have 10 songs to choose from, we get n, or 10, possible sets 16

Finally, here is the recursive definition of n choose k The recursive definition of n choose k summarizes all of these points: What is c(5, 2)? ____________ What is c(4, 1)? ____________ What is c(4, 2)? ____________ What is c(6, 3)? ___________ How many poker hands are possible?_____

But we don’t need recursion here either Could also use the factorial method at least for not large arguments Example: From 4, choose 2

Refactorings Refactoring: Making small changes to code without changing the meaning Two related refactorings from Martin Fowler's online refactoring catalog Replace recursion with iteration http://www.refactoring.com/catalog/replaceRecursionWithIteration.html Replace iteration with recursion http://www.refactoring.com/catalog/replaceIterationWithRecursion.html