Chapter 12. Recursion Basics of Recursion Programming with Recursion Computer Programming with JAVA.

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.
Recursion Chapter 11. Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar with the binary.
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.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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,
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Basics of Recursion l Programming with Recursion Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: 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.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
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.
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
1 Section 2.1 Algorithms. 2 Algorithm A finite set of precise instructions for performing a computation or for solving a problem.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
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,
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
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.
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,
Using recursion for Searching and Sorting
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter Topics Chapter 16 discusses the following main topics:
Recursion Version 1.0.
to understand recursion you must understand recursion
Recursion Topic 5.
Chapter 15 Recursion.
Recursion DRILL: Please take out your notes on Recursion
Chapter 15 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 Chapter 11.
The Basics of Recursion
Recursion Chapter 11.
Basics of Recursion Programming with Recursion
Recursion Chapter 11.
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Chapter 12. Recursion Basics of Recursion Programming with Recursion Computer Programming with JAVA

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

Recursive methods must eventually terminate A recursive method must have at least one base, or stopping, case. A base case does not execute a recursive call it stops the recursion 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

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

Example: a recursive method RecursionDemo (Display 12.1/page 642) 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 inWords definition calls itself: Here is the recursive call

Example: a base case 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 digit the if/else statement finally executes the base case and the algorithm terminates inWords definition (repeated from the previous slide): This is the base case for inWords (it executes when the argument has been reduced to only one digit) Recursive calls to inWords reduce the argument by one digit (integer division truncates)

Warning: infinite recursion may cause a stack overflow error If a recursive method is called and a base case never executes the method keeps calling itself The stack is a data structure that keeps track of recursive calls Every call puts data related to the call on the stack the data is taken off the stack only when the recursion stops So, if the recursion never stops the stack eventually runs out of space and a stack overflow error occurs on most systems

Recursive versus iterative methods All recursive algorithms/methods can be rewritten without recursion. Methods rewritten without recursion typically have loops, so they are called iterative methods Iterative methods generally run faster and use less memory space So when should you use recursion? when efficiency is not important and it makes the code easier to understand

Pseudocode for handling exceptions A common way of handling exceptions in Java: try { } catch(Exception_Class_Name e) { }

Example: code for handling exceptions in Java try { System.out.println("Enter a positive number:"); count = SavitchIn.readLineInt(); if(count <= 0) throw new Exception("Input not positive."); } catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Try again."); } There is more than one way to do this in Java code. One way is to use recursion.

Example: handling exceptions with recursion The objective of getCount is to display an error message if the user enters a non-positive integer and give the user another chance to enter an acceptable (positive) value getCount does the following: Reads an entry from the keyboard Throws NonpositiveException* if it is not a positive integer Calls itself in the catch block for NonpositiveException so the user gets another chance to enter a positive integer * See Display 12.6/page 660 for the definition of nonpositiveException getCount method from class CountDown (Display 12.5/page 659):

The "name in the phone book" problem revisited A recursive solution to the problem was shown in pseudocode on slide 4 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

Binary search algorithm 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 Sequential search: inefficient, but easy to understand and program Binary search: more efficient than sequential, but it only works if the list is sorted first! 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

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.

Example: binary search code The find method of ArraySearcher (Display 12.7/pages 664-5) implements a binary search algorithm It returns the index of the entry if the target value is found or -1 if it is not found Compare it to the pseudocode for the "name in the phone book" problem

Summary If a method definition includes an invocation of the very method being defined, the invocation is called a recursive call. Recursive calls are legal in Java and sometimes can make code easier to read. 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. Recursion can be a handy way to write code that says "if an exception is thrown, then start the whole process over again."