Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Recursion Chapter 11. Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar with the binary.
Chapter 9: Searching, Sorting, and Algorithm Analysis
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Recursion. Binary search example postponed to end of lecture.
Recursion Chapter 11 Chapter 11.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Programming with Recursion
Programming with Recursion. Example of Recursion (Ask Until the User Gets It Right) import java.util.* ; public class CountDown { private int count; public.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 249 Programming Methodology Chapter 10 – Recursion Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
M180: Data Structures & Algorithms in Java
Chapter 11- Recursion. Overview n What is recursion? n Basics of a recursive function. n Understanding recursive functions. n Other details of recursion.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
RECURSION. Objectives: become familiar with the idea of recursion Examine examples to show the wide variety of situations to which recursion can be applied.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
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.
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.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
1 Searching and Sorting Linear Search Binary Search.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
IB Computer Science Unit 5 – Advanced Topics Recursion.
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
Chapter 12. Recursion Basics of Recursion Programming with Recursion Computer Programming with JAVA.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Function Recursion to understand recursion you must understand recursion.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Recursion Powerful Tool
Using recursion for Searching and Sorting
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion Version 1.0.
to understand recursion you must understand recursion
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
The Basics of Recursion
Recursion Chapter 11.
Basics of Recursion Programming with Recursion
Recursion Chapter 11.
Comp 249 Programming Methodology
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Overview Recursion: a definition in terms of itself. Recursion in algorithms: l Recursion is a natural approach to some problems »it sounds circular, but in practice it is not l An algorithm is a step-by-step set of rules to solve a problem »it must eventually terminate with a solution l A recursive algorithm uses itself to solve one or more subcases Recursion in Java: l Recursive methods implement recursive algorithms l A recursive method is one whose definition includes a call to itself »a method definition with an invocation of the very method used to define it

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Recursive Methods Must Eventually Terminate A recursive method must have at least one base, or stopping, case. l A base case does not execute a recursive call »it stops the recursion l Each successive call to itself must be a "smaller version of itself" so that a base case is eventually reached »an argument must be made smaller each call so that eventually the base case executes and stops the recursion

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Example: a Recursive Algorithm One way to search a phone book (which is an alphabetically ordered list) for a name is with the following recursive algorithm: Search : middle page = (first page + last page)/2 Open the phone book to middle page; If (name is on middle page) then done; //this is the base case else if (name is alphabetically before middle page) last page = middle page //redefine search area to front half Search //recursive call with reduced number of pages else //name must be after middle page first page = middle page //redefine search area to back half Search //recursive call with reduced number of pages

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Example: A Recursive Method RecursionDemo is a class to process an integer and print out its digits in words »e.g. entering 123 would produce the output "one two three" inWords is the method that does the work of translating an integer to words Here is the recursive call: inWords definition calls itself

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Each recursive call to inWords reduces the integer by one digit »it drops out the least significant digit Eventually the argument to inWords has only one digit »the if/else statement finally executes the base case and the algorithm terminates Example: A Base Case Base case executes when only 1 digit is left Size of problem is reduced for each recursive call

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 7 What Happens with a Recursive Call Suppose that inWords is called from the main method of RecursionDemo with the argument 987 This box shows the code of inWords (slightly simplified) with the parameter numeral replaced by the argument 987 inWords(987) if (987 < 10) // print digit here else //two or more digits left { inWords(987/10); // print digit here } 1

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 8 What Happens with a Recursive Call The if condition is false, so the else part of the code is executed In the else part there is a recursive call to inWords, with 987/10 or 98 as the argument inWords(987) if (987 < 10) // print digit here else //two or more digits left { inWords(987/10); // print digit here } inWords(98) if (98 < 10) // print digit here else //two or more digits left { inWords(98/10); // print digit here } 2 Computation waits here until recursive call returns The argument is getting shorter and will eventually get to the base case.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 9 What Happens with a Recursive Call In the recursive call, the if condition is false, so again the else part of the code is executed and another recursive call is made. inWords(987) if (987 < 10) // print digit here else //two or more digits left { inWords(987/10); // print digit here } inWords(98) if (98 < 10) // print digit here else //two or more digits left { inWords(98/10); // print digit here } inWords(9) if (9 < 10) // print digit here else //two or more digits left { inWords(numeral/10); // print digit here } 3

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 10 inWords(9) if (9 < 10) // print nine else //two or more digits left { inWords(numeral/10); // print digit here } What Happens with a Recursive Call This time the if condition is true and the base case is executed. The method prints nine and returns with no recursive call. inWords(987) if (987 < 10) // print digit here else //two or more digits left { inWords(987/10); // print digit here } inWords(98) if (98 < 10) // print digit here else //two or more digits left { inWords(98/10); // print 98 % 10 } 4 Output: nine

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Output: nine eight What Happens with a Recursive Call The method executes the next statement after the recursive call, prints eight and then returns. inWords(98) if (98 < 10) // print out digit here else //two or more digits left { inWords(98/10); // print out 98 % 10 here } 5 inWords(987) if (987 < 10) // print out digit here else //two or more digits left { inWords(987/10); // print digit here }

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Output: nine eight seven What Happens with a Recursive Call l Again the computation resumes where it left off and executes the next statement after the recursive method call. It prints seven and returns and computation resumes in the main method. 6 inWords(987) if (987 < 10) // print out digit here else //two or more digits left { inWords(987/10); // print 987 % 10 } 6

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Remember : Key to Successful Recursion Recursion will not work correctly unless you follow some specific guidelines: The heart of the method definition can be an if-else statement or some other branching statement. l One or more of the branches should include a recursive invocation of the method. »Recursive invocations should use "smaller" arguments or solve "smaller" versions of the task. l One or more branches should include no recursive invocations. These are the stopping cases or base cases.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 14 Warning: Infinite Recursion May Cause a Stack Overflow Error l If a recursive method is called and a base case never executes, the method keeps calling itself l The stack is a data structure that keeps track of recursive calls l Every call puts data related to the call on the stack »the data is taken off the stack only when the recursion stops l So, if the recursion never stops, the stack eventually runs out of space »and a stack overflow error occurs on most systems

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Recursive Versus Iterative Methods All recursive algorithms/methods can be rewritten without recursion. l Methods rewritten without recursion typically have loops, so they are called iterative methods l Iterative methods generally run faster and use less memory space l So when should you use recursion? »when efficiency is not important and it makes the code easier to understand

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 16 numberOfZeros –A Recursive Method that Returns a Value takes a single int argument and returns the number of zeros in the number »example: numberOfZeros(2030) returns 2 l uses the following fact: If n is two or more digits long, then the number of zero digits is (the number of zeros in n with the last digit removed) plus an additional 1 if that digit is zero. Examples: »number of zeros in is number of zeros in 2003 plus 1 for the last zero »number of zeros in is number of zeros in 2003 plus 0 because last digit is not zero recursive

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 17 numberOfZeros public static int numberOfZeros(int n) { if (n==0) return 1; else if (n < 10) // and not 0 return 0; // 0 for no zeros else if (n%10 == 0) return (numberOfZeros(n/10) + 1); else // n%10 != 0 return (numberOfZeros(n/10)); } If n is two or more digits long, then the number of zero digits is (the number of zeros in n with the last digit removed) plus an additional 1 if that digit is zero. Which is (are) the base case(s)? Why? Which is (are) the recursive case(s)? Why?

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 18 public static int numberOfZeros(int n) { if (n==0) return 1; else if (n < 10) // and not 0 return 0; // 0 for no zeros else if (n%10 == 0) return (numberOfZeros(n/10) + 1); else // n%10 != 0 return (numberOfZeros(n/10)); } numberOfZeros(2005) is numberOfZeros(200) plus nothing numberOfZeros(200) is numberOfZeros(20) + 1 numberOfZeros(20) is numberOfZeros(2) + 1 numberOfZeros(2) is 0 (a stopping case) Recursive Calls Each method invocation will execute one of the if-else cases shown at right. Computation of each method is suspended until the recursive call finishes.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 19 public static int numberOfZeros(int n) { if (n==0) return 1; else if (n < 10) // and not 0 return 0; // 0 for no zeros else if (n%10 == 0) return (numberOfZeros(n/10) + 1); else // n%10 != 0 return (numberOfZeros(n/10)); } numberOfZeros(2) is 0 (a stopping case) numberOfZeros(20) is numberOfZeros(2) + 1, which is == 1 numberOfZeros(200) is numberOfZeros(20) + 1, which is == 2 numberOfZeros(2005) is numberOfZeros(200) plus nothing which is plus nothing == 2 Recursive Calls Returning Suspended computations completed as follows: (bottom to top on previous slide)

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Programming Tip : Ask Until the User Gets It Right getCount method from class CountDown public void getCount() { System.out.println("Enter a positive number:"); count = SavitchIn.readLineInt(); if (count <= 0) { System.out.println("Input must be positive. System.out.println("Try again."); getCount(); //start over } read a number Use a recursive call to get another number. Recursion continues until user enters valid input.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 21 The "Name in the Phone Book" Problem Revisited A recursive solution to the problem was shown in pseudocode on an earlier slide and is repeated here: Search: middle page = (first page + last page)/2 Open the phone book to middle page; If (name is on middle page) then done;//this is the base case else if (name is alphabetically before middle page) last page = middle page//redefine search area to front half Search//recursive call with reduced number of pages else //name must be after middle page first page = middle page//redefine search area to back half Search//recursive call with reduced number of pages

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Binary Search Algorithm l Searching a list for a particular value is a very common problem »searching is a thoroughly-studied topic »sequential and binary are two common search algorithms l Sequential search: inefficient, but easy to understand and program l Binary search: more efficient than sequential, but it only works if the list is sorted first! l The pseudocode for the "find the name in the phone book" problem is an example of a binary search »notice that names in a phone book are already sorted, so you may use a binary search algorithm

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Why Is It Called "Binary" Search? Compare sequential and binary search algorithms: How many elements are eliminated from the list each time a value is read from the list and it is not the "target" value? Sequential search: each time a value is read from the list and it is not the "target" value, only one item from the list is eliminated Binary search: each time a value is read from the list and it is not the "target" value, half the list is eliminated! That is why it is called binary - each unsuccessful test for the target value reduces the remaining search list by 1/2.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Binary Search Code The find method of ArraySearcher implements a binary search algorithm l It returns the index of the entry if the target value is found or -1 if it is not found l Compare it to the pseudocode for the "name in the phone book" problem

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch Indexes Contents target is 33 The array a looks like this: Binary Search Example mid = (0 + 9) / 2 (which is 4 ) 33 > a[mid] (that is, 33 > a[4] ) So, if 33 is in the array, then 33 is one of: Eliminated half of the remaining elements from consideration because array elements are sorted.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch Indexes Contents target is 33 The array a looks like this: Binary Search Example mid = (5 + 6) / 2 (which is 5 ) 33 == a[mid] So we found 33 at index 5 : 33 5 mid = (5 + 9) / 2 (which is 7 ) 33 < a[mid] (that is, 33 < a[7] ) So, if 33 is in the array, then 33 is one of: Eliminate half of the remaining elements

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 27 Merge Sort— A Recursive Sorting Method l Example of divide and conquer algorithm l Divides array in half and sorts halves recursively l Combines two sorted halves Merge Sort Algorithm to Sort the Array a If the array a has only one element, do nothing (stopping case). Otherwise, do the following (recursive case): Copy the first half of the elements in a to a smaller array named front. Copy the rest of the elements in the array a to another smaller array named tail. Sort the array front with a recursive call. Sort the array tail with a recursive call. Merge the elements in the arrays front and tail into the array a.

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 28 Merge Sort public static void sort(int[] a) { if (a.length >= 2) { int halfLength = a.length / 2; int[] front = new int[halfLength]; int[] tail = new int[a.length – halfLength]; divide(a, front, tail); sort(front); sort(tail); merge(a, front, tail); } // else do nothing. } recursive calls make "smaller" problems by dividing array base case: a.length == 1 so a is sorted and no recursive call is necessary. do recursive case if true, base case if false

Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 29 Summary l If a method definition includes an invocation of the very method being defined, the invocation is called a recursive call. l Recursive calls are legal in Java and sometimes can make code easier to read. l To avoid infinite recursion, a recursive method definition should contain two kinds of cases: one or more recursive calls and one or more stopping cases that do not involve any recursive calls. l Recursion can be a handy way to write code that says "if there is a problem then start the whole process over again."