Presentation is loading. Please wait.

Presentation is loading. Please wait.

AP Computer Science Instructor Alabama School of Fine Arts

Similar presentations


Presentation on theme: "AP Computer Science Instructor Alabama School of Fine Arts"— Presentation transcript:

1 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 "To iterate is human, to recurse divine.", L. Peter Deutsch

2

3 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.

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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); }

13 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

14 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; }

15 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

16 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));

17 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

18 /** */ 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.

19 • 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

20 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)

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

22 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

23 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

24 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) * (2 - (3 - (4 - 5)))

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

26 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

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

28 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

29 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 This is the recursive call. getFactorValue consumes the ) input getFactorValue returns 7 Continued

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

31 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?

32 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?

33 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") ?

34 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) ?

35 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?

36 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

37 (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

38 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

39 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

40 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

41 To understand recursion, you must first understand recursion.


Download ppt "AP Computer Science Instructor Alabama School of Fine Arts"

Similar presentations


Ads by Google