Module 09 - Recursion
Module 09 - Recursion
5th Edition
Module 9 -
Recursion
Including:
Chapter 9 – Recursion
Chapter 14 – Problem
Solving with Recursion
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
“To iterate is human, to recurse divine.” L. Peter Deutsch
2
3
4
What Is Recursion?
• Consider hiring a contractor to build
– He hires a subcontractor for a portion of the job
– That subcontractor hires a sub-subcontractor to do a
smaller portion of job
• The last sub-sub- … subcontractor finishes
– Each one finishes and reports “done” up the line
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Example: The Countdown
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Design Guidelines
• Method must be given an input value
• Method definition must contain logic that involves this
input, leads to different cases
• One or more cases should provide solution that does not
require recursion
– Else infinite recursion
• One or more cases must include a recursive invocation
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Programming Tip
• Iterative method contains a loop
• Recursive method calls itself
• Some recursive methods contain a loop and call
themselves
– If the recursive method with loop uses while, make
sure you did not mean to use an if statement
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Tracing a Recursive Method
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Stack of Activation Records
FIGURE 9-4 The stack of activation records during the execution of the call countDown(3)
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
A Methodized Approach to the Formulation of Recursive Algorithms
• Four steps
1. Determine the base case
2. Determine the reduced problem
3. Determine the general solution
4. Combine the base case, reduced problem and general
solution to form the recursive algorithm15
15
Determining the Base Case
16
16
Determining the Reduced Problem
18
18
Determining the Reduced Problem for n!
(the base case is 0!)
4! 24
return (4 * 3!) 6
return (3 * 2!) 2
return (2 * 1!) 1
return (1 * 0!) 1
0!
22
Recursive Methods That Return a Value
return sum;
} // end sumOf
• Base case
– Problems involving an integer n usually have their base case for
n=0 or n=1. Use n=0 because x^0 ≡ 1
• Reduced problem
•Candidates are x^(n-1), x^(n-2), x^(n-3)
•x^(n-1) is the only one that will become the base case for all n
• General solution
•xⁿ = x* [x^(n-1)] = x * reduced problem
• Combine
25
25
Recursive Coding of Xⁿ
1. public static float xToN(double x, int n)
2. { if(x == 0) // base case
3. return 1;
4. else
5. { int rp = xToN(x, n-1); // reduced problem (recursion)
6. float gs = x* rp; // calculate the general solution
7. return gs; // return the general solution
8. {
26
26
Recursive Algorithm for the nth Term, F n in the Fibonacci Sequence
(multiple base cases)
• Base case
– A defined solution for n = 0 and n = 1.
– F1 ≡ 1, F2 ≡ 1
• Reduced Problem
– Fn-1 and Fn-2 are close to original problem, and will
become one of the base cases when further reduced
• General solution (by definition)
– Fn ≡ Sum of reduced problems = Fn-1 + Fn-2
• Combine
27
27
Recursive Coding of the nth Term of the Fibonacci Sequence
FIGURE 9-6 Two arrays with their middle elements within their left halves
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Recursively Processing an Array
• Base case
– Problems involving an integer n usually have their
base case for n=0 or n=1. Use n = 0, no output
• Reduced problem
– Candidates are output n-1, or n-2, or n-3, …
characters in reverse order
– Output n-1 characters in reverse order is the only
one that will become the base case for all n
• General solution
– Output the nth character, output the first n-1
characters in reverse order
• Combine 34
34
Code to Output a String of Length n in Reverse Order
35
35
Code to Output a String of Length n in
Reverse Order (hidden base case)
36
37
Displaying a Bag
Display data in first node and recursively display data in rest of chain.
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Recursively Processing a Linked Chain
Displaying a chain backwards. Traversing chain of linked nodes in reverse order easier when
done recursively.
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Time Efficiency of Recursive Methods
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Using a Stack Instead of Recursion
• Converting a recursive method to an iterative one
public static void countDown(int integer)
{
if (integer >= 1)
{
System.out.println(integer);
countDown(integer - 1);
} // end if
} // end countDown
• An iterative version
public static void countDown(int integer)
{
while (integer >= 1)
{
System.out.println(integer);
integer = integer − 1;
} // end while
} // end countDown
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Using a Stack Instead of Recursion
• An iterative displayArray to maintain its own stack
public void displayArray(int first, int last)
{
boolean done = false;
StackInterface<Record> programStack = new LinkedStack<>();
programStack.push(new Record(first, last));
while (!done && !programStack.isEmpty())
{
Record topRecord = programStack.pop();
first = topRecord.first;
last = topRecord.last;
if (first == last)
System.out.println(array[first] + " ");
else
{
int mid = first + (last - first) / 2;
// Note the order of the records pushed onto the stack
programStack.push(new Record(mid + 1, last));
programStack.push(new Record(first, mid));
} // end if
} // end while
} // end displayArray
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Interesting Problems Whose Solutions Involve
Recursion
• Knight’s tour:
Q
– move a knight around a checkerboard such that it Q
Q
visits each square only once Q
Q
• Queens Eight: Q
Q
– Place eight queens on a checkerboard Q
3 4 9 5 6 7 1 2 8
• Numeric puzzle: 7
8
6
2
1
3
9
4
2
9
8
1
4
5
3
6
5
4 7 5 3 8 6 2 9 1
– Enter a 1, or 2, …, or 9 in each cell 1 9 6 7 5 2 3 8 4
6 1 4 2 7 3 8 5 9
• Towers
Move oneofring
Hanoi:
at a time, never placing a large ring
46
on a smaller ring 46
Simple Solution to a Difficult Problem
FIGURE 14-1 The initial configuration of the Towers of Hanoi for three disks
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simple Solution to a Difficult Problem
• Rules:
– Move one disk at a time. Each disk moved must be
the topmost disk.
– No disk may rest on top of a disk smaller than itself.
– You can store disks on the second (extra) pole
temporarily, as long as you observe the previous two
rules.
FIGURE 14-2 Sequence of moves for solving Towers of Hanoi problem with 3 disks
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simple Solution to a Difficult Problem (Part 2)
FIGURE 14-2 Sequence of moves for solving Towers of Hanoi problem with 3 disks
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
A Smaller Problem
FIGURE 14-3 The smaller problems in a recursive solution for four disks
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Solutions
Algorithm to move numberOfDisks disks from startPole to endPole using tempPole
as a spare according to the rules of the Towers of Hanoi problem
if (numberOfDisks == 1)
Move disk from startPole to endPole
else
{
Move all but the bottom disk from startPole to tempPole
Move disk from startPole to endPole
Move all disks from tempPole to endPole
}
• Base case S D E S D E
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Indirect Recursion
• Consider evaluation of validity of an algebraic expression
– Algebraic expression is either a term or two terms
separated by a + or – operator
– Term is either a factor or two factors separated by a *
or / operator
– Factor is either a variable or an algebraic expression
enclosed in parentheses
– Variable is a single letter
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Indirect Recursion
FIGURE 14-6 A two-dimensional maze with one entrance and one exit
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Backtracking