AP Computer Science Instructor Alabama School of Fine Arts

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Recursion.
Recursion - see Recursion. RHS – SOC 2 Recursion We know that: –We can define classes –We can define methods on classes –Mehtods can call other methods.
Chapter 18 Recursion "To iterate is human, to recurse divine.", L. Peter Deutsch.
CHAPTER 13 Recursion. Recursive Solution A recursive solution  solves a problem by solving a smaller instance of the problem. Example  How do we go.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Computer Science II Recursion Professor: Evan Korth New York University.
Recursion. Binary search example postponed to end of lecture.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
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.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
Copyright © 2003 Pearson Education, Inc. Slide 1.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
What is recursion? Imagine checking the dictionary for “apple”  a round fruit with a firm white flesh and a green, red or yellow skin  the usually sweet-tasting.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
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 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Lecture 10 Recursion CSE225: Data Structures. 2 A Look Back at Functions #include double distance(double x1, double y1, double x2, double y2) { double.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
CIS 068 Welcome to CIS 068 ! Stacks and 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 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Thirteen: Recursion.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
Chapter 18 Recursion. Chapter Goals To learn about the method of recursion To understand the relationship between recursion and iteration To analyze problems.
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.
Copyright © 2013 by John Wiley & Sons. All rights reserved. RECURSION CHAPTER Slides by Rick Giles 13.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is 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.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
CS 46B: Introduction to Data Structures June 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 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.
Copyright © 2013 by John Wiley & Sons. All rights reserved. RECURSION CHAPTER 11 May 27, 2013 Slides by James Tam Department of Computer Science, University.
Recursion Powerful Tool
Identify the Appropriate Method for Handling Repetition
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion - see Recursion
Recursion Version 1.0.
Chapter 13 Recursion.
Topic 6 Recursion.
Recursion DRILL: Please take out your notes on Recursion
Department of Computer Science,
Java 4/4/2017 Recursion.
To understand recursion, you have to understand recursion!
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion For some problems, it’s useful to have a method call itself.
Recursion - see Recursion
Advanced Java Programming
Basics of Recursion Programming with Recursion
Presentation transcript:

AP Computer Science Instructor Alabama School of Fine Arts A+ AP Computer Science A Review Sessions Session 2.2 Huntsville, Alabama March 5, 2011 Recursion Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts cyarbrough@asfa.k12.al.us "To iterate is human, to recurse divine.", L. Peter Deutsch

Recursion A recursive computation solves a problem by using the solution of the same problem with simpler values For recursion to terminate, there must be special cases for the simplest inputs.

Recursion Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems When the subproblems are small enough to solve directly the process stops A recursive algorithm is a problem solution that has been expressed in terms of two or more easier to solve subproblems

Recursion Example – Solving Factorials The problem of solving factorials is our first example of recursion. The factorial operation in mathematics is illustrated below. 1! = 1 2! = 2 * 1 or 2 * 1! 3! = 3 * 2 * 1 or 3 * 2! 4! = 4 * 3 * 2 *1 or 4 * 3! Notice that each successive line can be solved in terms of the previous line. For example, 4! is equivalent to the problem 4 * 3! Introduction to Java

Using A Recursive Method A recursive method to solve the factorial problem is given below. Notice in the last line of the method the recursive call. The method calls another implementation of itself to solve a smaller version of the problem. int fact(int n) // returns the value of n! // precondition: n >= 1 { if (n == 1) return 1; else return n * fact(n - 1); } The base case is a fundamental situation where no further problem solving is necessary. In the case of finding factorials, the answer of 1! is by definition == 1. No further work is needed. Introduction to Java

Recursion – Step By Step Suppose we call the method to solve fact(4). This will result in four calls of method fact. fact(4): This is not the base case (n==1) so we return the result of 4 * fact(3). This multiplication will not be carried out until an answer is found for fact(3). This leads to the second call of fact to solve fact(3). fact(3): Again, this is not the base case and we return 3 * fact (2). This leads to another recursive call to solve fact(2). fact(2): Still, this is not the base case, we solve 2 * fact(1). fact(1): Finally we reach the base case, which returns the value 1. Introduction to Java

Recursion – Step By Step When a recursive call is made, the current computation is temporarily suspended and placed on the stack with all its current information available for later use. A completely new copy of the method is used to evaluate the recursive call. When that is completed, the value returned by the recursive call is used to complete the suspended computation. The suspended computation is removed from the stack and its work now proceeds. When the base case is encountered the recursion will now unwind and result in a final answer. The expressions below should be read from right to left. fact(4) = 4 * fact(3) = 3 * fact(2) = 2 * fact(1) = 1 24  4 * 6  3 * 2  2 * 1 Introduction to Java

Recursion – The Picture Each box represents a call of method fact. To solve fact(4) requires four calls of method fact. Notice that when the recursive calls were made inside the else statement, the value fed to the recursive call was (n-1). This is where the problem is getting smaller and simpler with the eventual goal of solving 1!. Here is a picture. Look at what happens: Introduction to Java

Pitfalls Of Recursion If the recursion never reaches the base case, the recursive calls will continue until the computer runs out of memory and the program crashes. Experienced programmers try to examine the remains of a crash. The message “stack overflow error” or “heap storage exhaustion” indicates a possible runaway recursion. When programming recursively, you need to make sure that the algorithm is moving toward the base case. Each successive call of the algorithm must be solving a simpler version of the problem. Any recursive algorithm can be implemented iteratively, but sometimes only with great difficulty. However, a recursive solution will run more slowly than an iterative one because of the overhead of opening and closing the recursive calls. Introduction to Java

Recursion – Example #2 int result = identity(10); System.out.println("The final answer is " + result); public int identity(int num) { if (num < 1) return 10; else return num + identity(num - 2); } identity(num) returned value identity (0) 10 identity (2) 12 identity (4) 16 identity (6) 22 identity (8) 30 identity (10) 40 The final answer is 40. Introduction to Java

Evaluating Exponents Recursively static int power(int k, int n) { // raise k to the power n if (n == 0) return 1; else return k * power(k, n – 1); }

Divide and Conquer Using this method each recursive subproblem is about one-half the size of the original problem If we could define power so that each subproblem was based on computing kn/2 instead of kn – 1 we could use the divide and conquer principle Recursive divide and conquer algorithms are often more efficient than iterative algorithms

Evaluating Exponents Using Divide and Conquer static int power(int k, int n) { // raise k to the power n if (n == 0) return 1; else{ int t = power(k, n/2); if ((n % 2) == 0) return t * t; else return k * t * t; }

Thinking Recursively Problem: test whether a sentence is a palindrome Palindrome: a string that is equal to itself when you reverse all characters A man, a plan, a canal–Panama! Go hang a salami, I'm a lasagna hog Madam, I'm Adam

Sentence shorter = new Sentence(text.substring(1,length-1)); public boolean isPalindrome() { int length = text.length(); if( length <= 1 ) return true; char first = Character.toLowerCase(text.charAt(0)); char last = Character.toLowerCase(text.charAt(length-1)); if (Character.isLetter(first) && Character.isLetter(last)) { if( first == last ) { Sentence shorter = new Sentence(text.substring(1,length-1)); return shorter.isPalindrome(); } else return false; else if(!Character.isLetter(last)) { Sentence shorter = new Sentence(text.substring(0,length-1)); else { // Remove first character Sentence shorter = new Sentence(text.substring(1));

Recursive Helper Methods Sometimes it is easier to find a recursive solution if you make a slight change to the original problem • We will change the palindrome checker so you specify the start and end indices of the substring to check • Rather than passing the entire substring as an argument

/** */ This is what we call a recursive helper method. Test whether a substring of the sentence is a palindrome. @param start the index of the first character of the substring @param end the index of the last character of the substring @return true if the substring is a palindrome */ public boolean isPalindromeHelper(int start int end) This is what we call a recursive helper method.

• Start the recursion off by calling the main recursive function eg. isPalindrome(). The main recursive function doesn’t actually call itself. Instead, it just gets the recursion started • It calls the helper function with initial parameters eg. isPalindromeHelper(0, text.length() – 1) • The helper function is recursive -- it calls itself eg. isPalindromeHelper calls itself

The Efficiency of Recursion Recursive divide and conquer algorithms are often more efficient than iterative algorithms (binary searches, divide & conquer exponentiation ) In many cases, a recursive solution is easier to understand and implement correctly than an iterative solution Often, however, recursive methods can be less efficient than their iterative counterparts Consider computing Fibonacci numbers fib(n) = fib(n-1) + fib(n-2)

Call Tree for Computing fib(6) See Jeliot animation of fib() Figure 2: Call Tree of the Recursive fib method

The Efficiency of Recursion Method takes so long because it computes the same values over and over The computation of fib(6) calls fib(3) three times Imitate the pencil-and-paper process to avoid computing the values more than once

The Efficiency of Recursion Occasionally, a recursive solution runs much slower than its iterative counterpart In most cases, the recursive solution is only slightly slower The iterative isPalindrome performs only slightly better than recursive solution Each recursive method call takes a certain amount of processor time

Using Mutual Recursions Problem: to compute the value of arithmetic expressions such as Computing expression is complicated * and / bind more strongly than + and - parentheses can be used to group subexpressions 3 + 4 * 5 (3 + 4) * 5 1 - (2 - (3 - (4 - 5)))

Syntax Diagram for Evaluating an Expression Figure 5: Syntax Diagrams for Evaluating an Expression

Using Mutual Recursions An expression can broken down into a sequence of terms, separated by + or - Each term is broken down into a sequence of factors, separated by * or / Each factor is either a parenthesized expression or a number The syntax trees represent which operations should be carried out first

Syntax Tree for Two Expressions Figure 6: Syntax Trees for Two Expressions

Mutually Recursive Methods In a mutual recursion, a set of cooperating methods calls each other repeatedly To compute the value of an expression, implement 3 methods that call each other recursively getExpressionValue getTermValue getFactorValue

Using Mutual Recursions To see the mutual recursion clearly, trace through the expression (3+4)*5: getExpressionValue calls getTermValue getTermValue calls getFactorValue getFactorValue consumes the ( input getFactorValue calls getExpressionValue getExpressionValue returns eventually with the value of 7, having consumed 3 + 4. This is the recursive call. getFactorValue consumes the ) input getFactorValue returns 7 Continued

Using Mutual Recursions getTermValue consumes the inputs * and 5 and returns 35 getExpressionValue returns 35

Tracing Recursive Methods Functional #1   public int f1(int n) { if (n == 0) return 0; return 5 + f1(n-1); } What is f1(3) ? What does f1 compute?

Functional #4 public int f4(int n) { if (n == 0 || n == 1) return 1; return f4(n-1) + f4(n-2); } What is f4(5) ? What does f4 compute? Draw the execution tree for f4(5)? Why is f4 so inefficient?

String #1   public String s1(String s) { if (s.length() == 0) return ""; return s.substring(0, 1) + s1(s.substring(1)); } What is s1("cat") ?

Arrays and ArrayLists #1   public int a1(int[] a, int n) { if (n == 0) return a[0]; int m = a1(a, n-1); if (m > a[n]) return m; else return a[n]; } What is a1(new int[]{4, 1, -3, 2}, 3) ?

Printing #1 public void p1(int n) { if (n > 1) p1(n-1); System. out Printing #1 public void p1(int n) { if (n > 1) p1(n-1); System.out.print(n); } What does p1(4) print? What does p1(5) print?

Recursive problems from APCS A 2008 Exam 39. Consider the following recursive method.   public int recur(int n) { if (n <= 10) return n * 2; else return recur(recur(n / 3)); } What value is returned as a result of the call recur(27) ? (A) 8 (B) 9 (C) 12 (D) 16 (E) 18

(C) W WA (E)WATCH WATC WAT WAT WATC WA (D) W WA W WATC WATCH 40. Consider the following recursive method.  public static void whatsItDo(String str) { int len = str.length(); if (len > 1) { String temp = str.substring(0, len - 1); whatsItDo(temp); System.out.println(temp); }  What is printed as a result of the call whatsItDo("WATCH")? (A) WATC WAT WA W (B) WATCH WATC WAT WA (C) W WA WAT WATC (D) W WA WATC WATCH (E)WATCH WATC WAT WA W WATC WATCH

Recursive problems from APCS AB 2008 Exam 13. Consider the following method. // Precondition: b > 0 public int surprise(int b) { if ((b % 2) == 0) { if (b < 10) return b; else return ((b % 10) + surprise(b / 10)); } else { if (b < 10) return 0; else return surprise(b / 10); Which of the following expressions will evaluate to true? I. surprise(146781) == 0 II. surprise(7754) == 4 III. surprise(58216) == 16 (A) I only (B) II only (C) III only (D) II and III only (E) I, II, and III  

18. Consider the following method. public String recScramble(String str, int[] positions, int k) { if (str == null || str.length() == 0) return ""; if (str.length() == 1) return str; int pos = positions[k]; String nStr = str.substring(pos, pos + 1); str = str.substring(0, pos) + str.substring(pos + 1);   return nStr + recScramble(str, positions, k + 1); } Consider the following code segment. int[] indexes = {2, 1, 1}; System.out.println(recScramble("epic", indexes, 0)); What is printed as a result of executing the code segment? (A) cepi (B) epci (C) iecp (D) iepc (E) ipce

20. Consider the following method 20. Consider the following method. public int addFun(int n) { if (n <= 0) return 0; if (n == 1) return 2; return addFun(n - 1) + addFun(n - 2); } What value is returned as a result of the call addFun(6) ? (A) 10 (B) 12 (C) 16 (D) 26 (E) 32

To understand recursion, you must first understand recursion.