Ch. 3: Recursion. Recursive Solutions Recursion –An extremely powerful problem-solving technique –Breaks a problem into smaller identical problems –An.

Slides:



Advertisements
Similar presentations
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Advertisements

COMPSCI 105 S Principles of Computer Science Recursion 1.
Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
Recursion Chapter 8. 2 Chapter Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an.
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.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Programming with Recursion
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
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.
Recursion.
Recursion. Recursive Solutions Recursion breaks a problem into smaller identical problems – mirror images so to speak. By continuing to do this, eventually.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors.
COMPSCI 105 S Principles of Computer Science Recursion 3.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
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.
CENG 7071 Recursion. CENG 7072 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive function.
Functions in C++ Eric Roberts CS 106B January 9, 2013.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursion: The Mirrors Chapter 2.
Recursion: The Mirrors Chapter 2 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
© 2006 Pearson Addison-Wesley. All rights reserved 3-1 Chapter 3 Recursion: The Mirrors.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursion: The Mirrors Chapter 2.
Chapter 3 Recursion: The Mirrors. © 2004 Pearson Addison-Wesley. All rights reserved 3-2 Recursive Solutions Recursion –An extremely powerful problem-solving.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Lecture 10 Recursion CSE225: Data Structures. 2 A Look Back at Functions #include double distance(double x1, double y1, double x2, double y2) { double.
COSC 2006 Data Structures I Recursion II
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors Data Abstraction & Problem Solving.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Recursive Solutions Recursion is an extremely powerful problem-solving.
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
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.
Concepts of Algorithms CSC-244 Unit 5 and 6 Recursion Shahid Iqbal Lone Computer College Qassim University K.S.A.
Ramamurthy Recursion: The Mirrors B. Ramamurthy CS114A,B.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion Powerful Tool
Programming with Recursion
Recursion.
CSC 205 Programming II Lecture 8 Recursion.
Recursion CENG 707.
Recursion CENG 707.
Recursion: The Mirrors
Recursion: The Mirrors
Methods Chapter 6.
Recursion: The Mirrors
Recursion: The Mirrors
Recursion: The Mirrors
Chapter 18 Recursion.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Recursion: The Mirrors
Presentation transcript:

Ch. 3: Recursion

Recursive Solutions Recursion –An extremely powerful problem-solving technique –Breaks a problem into smaller identical problems –An alternative to iteration, but not always a better one An iterative solution involves loops "Recursion can provide elegantly simple solutions to problems of great complexity. However, some recursive solutions are impractical because they are so inefficient."

Four questions for constructing recursive solutions 1.Can you define the problem in terms of a smaller problem of the same type? 2.Does each recursive call diminish the size of the problem? 3.What instance of the problem can serve as the base case? 4.As the problem size diminishes, will you reach this base case? Recursive Solutions

Binary Search vs Sequential Search Some complex and time-consuming problems have recursive solutions that are very simple A running example that the author uses in Ch. 3 is Binary Search. Suppose you are given a sequence of values that are stored in non-decreasing order and you want to locate a particular value in that sequence.

Binary Search A high-level binary search of an in-order array if (anArray is of size 1) { Determine if anArray’s item is equal to value } else { Find the midpoint of anArray Determine which half of anArray contains value if (value is in the first half of anArray) { binarySearch (first half of anArray, value) } else { binarySearch(second half of anArray, value) } // end if Binary search is an example of a "divide-and-conquer" solution

1.One of the actions in the method is to call itself, one or more times = a recursive call. 2.Each successive recursive call involves an identical, but smaller problem. 3.Recursion ends when the problem size satisfies a condition identifying a single base case or one of a number of base cases. 4.Eventually, a base case is executed and the recursion stops. Characteristics of Recursive Methods

Recursive Functions The easiest examples of recursion to understand are functions in which the recursion is clear from the definition. As an example, consider the factorial function, which can be defined in either of the following ways: n! = n x (n - 1) x (n - 2) x... x 3 x 2 x 1 n! = n x (n - 1)! 1 if n is 0 otherwise The second definition leads directly to the following code: public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); }

Methods that don't need access to instance variables and are self-contained (depending only on parameter input) are good candidates to be designated as static methods. All the recursive methods in Ch. 3 of our book are declared static because they only depend on parameter values. Static methods can be easily tested with DrJava. Static Methods

Simulating the factorial Method skip simulation Factorial Enter n: 5 5! = 120 public void calcFactorial() { int n = this.readInt("Enter n: "); println(n + "! = " + factorial(n) ); } n private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 5 24 private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 4 6 private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 3 2 private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 2 1 private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 1 1 private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 0 private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } n 0

The Recursive “Leap of Faith” The purpose of going through the complete decomposition of the calculation of factorial(5) is to convince you that the process works and that recursive calls are in fact no different from other method calls, at least in their internal operation. Our book uses a systematic trace of recursive methods called a box trace, very similar to the method stack shown on the last slide. As you write a recursive program, it is important to believe that any recursive call will return the correct answer as long as the arguments continually get closer to a stopping condition. Believing that to be true—even before you have completed the code—is called the recursive leap of faith.

The Recursive Paradigm Most recursive methods you encounter in an introductory course have bodies that fit the following general pattern: if ( test for a simple case ) { Compute and return the simple solution without using recursion. } else { Divide the problem into one or more subproblems that have the same form. Solve each of the subproblems by calling this method recursively. Return the solution from the results of the various subproblems. } Finding a recursive solution is mostly a matter of figuring out how to break it down so that it fits the paradigm. When you do so, you must do two things: Identify simple cases that can be solved without recursion.1. Find a recursive decomposition that breaks each instance of the problem into simpler subproblems of the same type, which you can then solve by applying the method recursively. 2.

Tracing Recursive Methods Box trace –A systematic way to trace the actions of a recursive method –Each box roughly corresponds to an activation record –An activation record Contains a method’s local environment at the time of and as a result of the call to the method

1.Label each recursive call in the body of the recursive method. 2.Represent each call to the method by a new box containing the method's local environment. a)values of local variables and parameters b)placeholder for return value and operation performed 3.Draw an arrow from box to box, where each represents another recursive call. 4.Cross off boxes as methods return Box Trace

Tracing the fact method A method’s local environment includes: –The method’s local variables –A copy of the actual value arguments –A return address in the calling routine –The value of the method itself n = 3 A: fact(n-1) = ? return 3 * ?

Recursive Methods As a programmer, you need to ensure that all recursive calls bring the execution closer to the stopping condition. The simpler cases must eventually reach the stopping condition or the method will call itself infinitely. In Java, when a method calls itself a very large number of times, the stack gets full and a "Stack Overflow" occurs.

A Recursive void Method: Writing a String Backward Problem Given a string of characters, print it in reverse order Recursive solution Each recursive step of the solution diminishes by 1 the length of the string to be written backward Base case Print the empty string backward

Iterative Version This is an iterative method to print a String in reverse public static void writeStringBackwards(String s) { for (int i = s.length()-1; i >= 0; i--) { System.out.print(s.charAt(i)); } System.out.println(); }

Recursive Version This is a recursive method to print a String in reverse public static void writeBackward(String s, int size) { if (size==0) { System.out.println(); } else { // print the last character System.out.print(s.substring(size-1, size)); // write the rest of the string in reverse writeBackward(s, size - 1); } In this example, the base case is reached when size = 0. The recursive call is made on the input string minus the last character (str length is closer to the empty string).

Recursive Version This is another recursive method to print a String in reverse public static void writeBackward(String s) { if (s.length() > 0) { // write the rest of the string backward writeBackward(s.substring(1)); // print the first character System.out.print(s.charAt(0)); } System.out.println(); } Like the last example, the base case is reached when size = 0. The recursive call is made on the input string minus the first character (str length is closer to the empty string).

Recursive Methods This is a recursive method to reverse a String, returning a String instead of printing one out. public static String recRevString(String str) { if (str.length() == 0) { return ""; } else { return recRevString(str.substring(1)) + str.charAt(0); } In this example, the base case is reached when the length of the input string is zero. The recursive call is made on the input string minus the first character (str length is closer to the empty string).

Recursive Methods Exercise: Write a recursive method to return the sum of all the numbers between 1 and n private static int recSum(int n) { if (n == 0) { return 0; } else { return n + recSum(n-1); } In this example, the stopping case is reached when the input parameter n is equal to 0.

Recursive Methods Exercise: Write a recursive method to return the sum of all the numbers in a given input array private static int recSumArray(int[] arr, int j) { if (j == arr.length) { return 0; } else { return arr[j] + recSumArray(arr,j+1); } In this example, the stopping case is reached when the input parameter j is equal to the length of the array and the recursive call is made by passing in the array and j incremented by 1, bringing j closer to the stopping case.

Recursive Methods Exercise: Write a recursive method to raise a base to an exponent power private static double recPower(double base, int exponent) { if (exponent == 0) { return 1; } else { return base * this.recPower( base, exponent - 1); } These examples illustrate the essential features of a recursive method: 1. A base case that has no recursive call. 2. A recursive case that contains a call to the containing method, passing in an argument that is closer to the base case than the value of the current parameter.

Recursive Methods Exercise: Write a recursive method to determine if a given String is a palindrome. private boolean isPalindrome(String str) { if (str.length() == 0 || str.length() == 1) { return true; } else { return(str.charAt(0) == str.charAt(str.length()-1)) && this.isPalindrome(str.substring(1,str.length()-1)); } In this example, there are two base cases; one for even- and one for odd-length palindromes. The recursive call is made on the input string minus the first and last character (str is closer to the empty string on every call).

Next three problems –Require you to count certain events or combinations of events or things –Contain more than one base cases –Are good examples of inefficient recursive solutions

Multiplying Rabbits (The Fibonacci Sequence) “Facts” about rabbits –Rabbits never die –A rabbit reaches sexual maturity exactly two months after birth, that is, at the beginning of its third month of life –Rabbits are always born in male-female pairs At the beginning of every month, each sexually mature male-female pair gives birth to exactly one male-female pair

Multiplying Rabbits (The Fibonacci Sequence) Problem How many pairs of rabbits are alive in month n? Recurrence relation rabbit(n) = rabbit(n-1) + rabbit(n-2)

Multiplying Rabbits (The Fibonacci Sequence)

Base cases rabbit(2), rabbit(1) Recursive definition rabbit(n) = 1if n is 1 or 2 rabbit(n-1) + rabbit(n-2)if n > 2 Fibonacci sequence The series of numbers rabbit(1), rabbit(2), rabbit(3), and so on NOT an efficient solution for this problem because each solution requires many redundant computations

Organizing a Parade Rules about organizing a parade The parade will consist of bands and floats in a single line One band cannot be placed immediately after another Problem How many ways can you organize a parade of length n?

Organizing a Parade Let: P(n) be the number of ways to organize a parade of length n F(n) be the number of parades of length n that end with a float B(n) be the number of parades of length n that end with a band Then P(n) = F(n) + B(n)

Finding the largest item in an array if (array has only one item) max(array) is the item else max(array) is the maximum of max(left half of array) and max(right half of array)

Mr. Spock’s Dilemma (Choosing k out of n Things) Problem How many different choices are possible for exploring k planets out of n planets in a solar system? Let c(n, k) be the number of groups of k planets chosen from n

Mr. Spock’s Dilemma (Choosing k out of n Things) In terms of Planet X: c(n, k) = (the number of groups of k planets that include Planet X) + (the number of groups of k planets that do not include Planet X)

Mr. Spock’s Dilemma (Choosing k out of n Things) The number of ways to choose k out of n things is the sum of The number of ways to choose k-1 out of n-1 things and The number of ways to choose k out of n-1 things c(n, k) = c(n-1, k-1) + c(n-1, k)

The End