Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 13 Recursion. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Recursive void Functions Tracing recursive.
Recursion in Python. Recursion Problems in every area of life can be defined recursively, that is, they can be described in terms of themselves. An English.
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
Recursion. Binary search example postponed to end of lecture.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search -Reading p
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
CSC1016 Welcome (again!) Get course notes handout (and read them) The question of whether computers can think is like the question of whether submarines.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: 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.
Recursion.  A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0)
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.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 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.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
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.
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 12. Recursion Basics of Recursion Programming with Recursion Computer Programming with JAVA.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Slide 1 Chapter 13 Recursion Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
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.
Function Recursion to understand recursion you must understand recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
to understand recursion you must understand recursion
Recursion DRILL: Please take out your notes on Recursion
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
Chapter 14 Recursion 1.
CIS Principles of Programming
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
to understand recursion you must understand recursion
Recursion This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the instructor’s class materials.
The Basics of Recursion
Basics of Recursion Programming with Recursion
Programming with Recursion
Chapter 14 Recursion 1.
Programming with Recursion
Comp 249 Programming Methodology
Chapter 14 Recursion 1.
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 14 Recursion 1.
Presentation transcript:

Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11-2 Recursion You’ve seen recursive problem solving techniques used before in math

n! (n factorial) n! for some non negative integer n is defined as: 0! = 1for n = 0 1! = 1for n = 1 n! = n * (n-1)! for all other n > 1

Fibonacci numbers The sequence of Fibonacci numbers begins: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,...

Recursive void Methods A recursive method is a method that includes a call to itself Recursion is based on the general problem solving technique of breaking down a task into subtasks – In particular, recursion can be used whenever one subtask is a smaller version of the original task 11-5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Vertical Numbers The static recursive method writeVertical takes one (nonnegative) int argument, and writes that int with the digits going down the screen one per line Note: Recursive methods need not be static This task may be broken down into the following two subtasks Simple case: If n<10, then write the number n to the screen Recursive Case: If n>=10, then do two subtasks: Output all the digits except the last digit Output the last digit 11-6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Vertical Numbers Given the argument 1234, the output of the first subtask would be: The output of the second part would be: Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Vertical Numbers The decomposition of tasks into subtasks can be used to derive the method definition: – Subtask 1 is a smaller version of the original task, so it can be implemented with a recursive call – Subtask 2 is just the simple case 11-8 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Algorithm for Vertical Numbers Given parameter n in writeVertical if (n<10) System.out.println(n); else { writeVertical (the number n with the last digit removed); System.out.println(the last digit of n); } 11-9 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11-10 Program for Vertical Numbers public static void writeVertical(int n) { if (n < 10) // base/termination case { System.out.println(n); } else // n is two or more digits long: recursive step { writeVertical( n/10 ); System.out.println(n%10 ); } }

Execution of writeVertical(123) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Execution of writeVertical(12) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Execution of writeVertical(1) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Completion of writeVertical(12) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Completion of writeVertical(123) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Closer Look at Recursion The computer keeps track of recursive calls as follows: – When a method is called, the computer plugs in the arguments for the parameter(s), and starts executing the code – If it encounters a recursive call, it temporarily stops (suspends) its computation – When the recursive call is completed, the computer returns to finish the suspended computation Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Closer Look at Recursion When the computer encounters a recursive call, it must temporarily suspend its execution of a method – It does this because it must know the result of the recursive call before it can proceed – It saves all the information it needs to continue the computation later on, when it returns from the recursive call Ultimately, this entire process terminates when one of the recursive calls does not depend upon recursion to return Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pitfall: Infinite Recursion In the writeVertical example, the series of recursive calls eventually reached a call of the method that did not involve recursion (a stopping case) If, instead, every recursive call had produced another recursive call, then a call to that method would, in theory, run forever – This is called infinite recursion – In practice, such a method runs until the computer runs out of resources, and the program terminates abnormally Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pitfall: Infinite Recursion An alternative version of writeVertical – Note: No stopping case! public static void newWriteVertical(int n) { newWriteVertical(n/10); System.out.println(n%10); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Stacks for Recursion To keep track of recursion (and other things), most computer systems use a stack – A stack is a very specialized kind of memory structure analogous to a stack of paper – As an analogy, there is also an inexhaustible supply of extra blank sheets of paper – Information is placed on the stack by writing on one of these sheets, and placing it on top of the stack (becoming the new top of the stack) – More information is placed on the stack by writing on another one of these sheets, placing it on top of the stack, and so on Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Stacks for Recursion – To get information out of the stack, the top paper can be read, but only the top paper – To get more information, the top paper can be thrown away, and then the new top paper can be read, and so on Since the last sheet put on the stack is the first sheet taken off the stack, a stack is called a last-in/first-out memory structure (LIFO) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Stacks for Recursion To keep track of recursion, whenever a method is called, a new "sheet of paper" is taken – The method definition is copied onto this sheet, and the arguments are plugged in for the method parameters – The computer starts to execute the method body – When it encounters a recursive call, it stops the computation in order to make the recursive call – It writes information about the current method on the sheet of paper, and places it on the stack Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Stacks for Recursion Depending on how many recursive calls are made, and how the method definition is written, the stack may grow and shrink in any fashion The stack of paper analogy has its counterpart in the computer – The contents of one of the sheets of paper is called a stack frame or activation record – The stack frames don't actually contain a complete copy of the method definition, but reference a single copy instead Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pitfall: Stack Overflow There is always some limit to the size of the stack – If there is a long chain in which a method makes a call to itself, and that call makes another recursive call,..., and so forth, there will be many suspended computations placed on the stack – If there are too many, then the stack will attempt to grow beyond its limit, resulting in an error condition known as a stack overflow A common cause of stack overflow is infinite recursion Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Recursion Versus Iteration Recursion is not absolutely necessary – Any task that can be done using recursion can also be done in a nonrecursive manner – A nonrecursive version of a method is called an iterative version An iteratively written method will typically use loops of some sort in place of recursion A recursively written method can be simpler, but will usually run slower and use more storage than an equivalent iterative version Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Iterative version of writeVertical Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Recursive Methods that Return a Value Recursion is not limited to void methods A recursive method can return a value of any type An outline for a successful recursive method that returns a value is as follows: – One or more cases in which the value returned is computed in terms of calls to the same method – the arguments for the recursive calls should be intuitively "smaller“ – One or more cases in which the value returned is computed without the use of any recursive calls (the base or stopping cases) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11-28 The Recursive Method power public static int power(int x, int n) { if (n < 0) { System.out.println("Illegal argument to power."); System.exit(0); } if (n == 0) //base return (1); else // n > 0 return ( power(x, n - 1) * x ); }

The Recursive Method power (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The Recursive Method power (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Evaluating the Recursive Method Call power(2,3) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11-32 Linear Search Linear search searches an array to find a specified value (a key) The array need not be a sorted array: If the value is found, its index is returned If the value is not found, -1 is returned Linear Search is very slow if there is a large number of elements in the array.

Binary Search Binary search uses a recursive method to search an array to find a specified value The array must be a sorted array: a[0]≤a[1]≤a[2]≤... ≤ a[finalIndex] If the value is found, its index is returned If the value is not found, -1 is returned Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Binary Search An algorithm to solve this task looks at the middle of the array or array segment first If the value looked for is smaller than the value in the middle of the array – Then the second half of the array or array segment can be ignored – This strategy is then applied to the first half of the array or array segment Note: Each execution of the recursive method reduces the search space by about a half Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Binary Search If the value looked for is larger than the value in the middle of the array or array segment – Then the first half of the array or array segment can be ignored – This strategy is then applied to the second half of the array or array segment If the value looked for is at the middle of the array or array segment, then it has been found If the entire array (or array segment) has been searched in this way without finding the value, then it is not in the array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pseudocode for Binary Search Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Recursive Method for Binary Search Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Execution of the Method search (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Execution of the Method search (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11-40 Execution of the Method search (What if key = 64 ?)

Efficiency of Binary Search Given an array with 1,000 elements, the binary search will only need to compare about 10 array elements to the key value, as compared to an average of 500 for a serial (linear) search algorithm The binary search algorithm has a worst-case running time that is logarithmic: O(log n) – A serial search algorithm is linear: O(n) If desired, the recursive version of the method search can be converted to an iterative version that will run more efficiently Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Iterative Version of Binary Search (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Iterative Version of Binary Search (Part 2 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

More Examples Copyright © 2008 Pearson Addison-Wesley. All rights reserved

n! (n factorial) n! for some non negative integer n can be rewritten as: 0! = 1for n = 0 1! = 1for n = 1 n! = n * (n-1)! for all other n > 1

Let’s code n! (n factorial) n! for some non negative integer n can be rewritten as: 0! = 1for n = 0 1! = 1for n = 1 n! = n * (n-1)! for all other n > 1 public static int Factorial ( int n ) { //base cases if (n==0)return 1; if (n==1)return 1; return n * Factorial( n-1 ); } This is an example of a recursive function (a function that calls itself)! To use this function: int result = Factorial( 10 );

Triangular numbers The triangular number T n can be represented in the form of a triangular grid of points where the first row contains a single element and each subsequent row contains one more element than the previous one. The triangular numbers are therefore 1, 1+2, 1+2+3, ,..., so the first few triangle numbers are 1, 3, 6, 10, 15, 21,...

Triangular numbers which can also be expressed as: T n = 1for n = 1 T n = n + T n-1 for n > 1

Fibonacci numbers The sequence of Fibonacci numbers begins: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...

A note regarding recursion... Calculations such as factorial, Fibonacci numbers, etc. are fine for introducing the idea of recursion. But the real power of recursion is in traversing advanced data structures such as trees (covered in more advanced classes and used in such applications as language parsing, games, etc.).

/** * Chapter 11 programming Project 1 * * This program recursively computes compound interest.. * */ import java.util.Scanner; public class Question1Interest { /** * calculateSavings * Recursively compute compound interest. * The recursive definition is: * savings(d,i,y) = savings((d*i)+d,i,y-1) * where d = initial deposit, i = interest rate, y = number of years initial_deposit Initial amount of deposit yearly_interest_rate Interest rate, value between 0-1 num_years integer that is number of years double Savings accrued at the interest rate after the number of years */

public static double calculateSavings(double initial_deposit, double yearly_interest_rate, int num_years) { // Base case -- if num_years = 0, then we just get the amount of // the initial deposit if (num_years == 0) return initial_deposit; // If num_years > 0, then for the first year we make // (interest_rate * initial_deposit) + initial_deposit. Feed this into the // same function, but now for one fewer year since we have accounted // for the value after this year. else return calculateSavings( (initial_deposit * yearly_interest_rate) + initial_deposit, yearly_interest_rate, num_years - 1); }

public static double calculateSavings(double initial_deposit, double yearly_interest_rate, int num_years) { if (num_years == 0) return initial_deposit; else return calculateSavings( ( initial_deposit * yearly_interest_rate) + initial_deposit, yearly_interest_rate, num_years - 1 ) ; }

// ====================== // main method // ====================== public static void main(String[] args) { // Input variables double initial_amount; double interest_rate; int num_years; double future_value; Scanner scan = new Scanner(System.in); System.out.println("Enter initial amount to save:"); initial_amount = scan.nextDouble(); System.out.println("Enter yearly interest rate (e.g for 10%)"); interest_rate = scan.nextDouble(); System.out.println("Enter number of years of compounded interest. "); num_years = scan.nextInt(); future_value = calculateSavings(initial_amount, interest_rate, num_years); System.out.println("$" + initial_amount + " after " + num_years + " years, at " + interest_rate + " would amount to $" + future_value); } } // Question1Interest