CH 05
CH 05
Chapter 5
Chapter Objectives
To understand how to think recursively
To learn how to trace a recursive method
To learn how to write recursive algorithms and methods for
searching arrays
To learn about recursive data structures and recursive
methods for a LinkedList class
To understand how to use recursion to solve the Towers of
Hanoi problem
To understand how to use recursion to process two-
dimensional images
To learn how to apply backtracking to solve search
problems such as finding a path through a maze
Recursion
Recursion can solve many programming problems that are difficult
to conceptualize and solve linearly
In the field of artificial intelligence, recursion often is used to write
programs that exhibit intelligent behavior:
playing games of chess
proving mathematical theorems
recognizing patterns, and so on
Recursive algorithms can
compute factorials
compute a greatest common divisor
process data structures (strings, arrays, linked lists, etc.)
search efficiently using a binary search
find a path through a maze, and more
Recursive Thinking
Section 5.1
Recursive Thinking
Recursion is a problem-solving approach that can
be used to generate simple solutions to certain
kinds of problems that are difficult to solve by
other means
Recursion reduces a problem into one or more
simpler versions of itself
Recursive Thinking (cont.)
Recursive Algorithm to Process Nested Figures
if there is one figure
do whatever is required to the figure
else
do whatever is required to the outer figure
process the figures nested inside the outer figure
in the same way
Recursive Thinking (cont.)
Consider searching for a target value in an array
Assume the array elements are sorted in increasing
order
We compare the target to the middle element and, if
the middle element does not match the target, search
either the elements before the middle element or the
elements after the middle element
Instead of searching n elements, we search n/2
elements
Recursive Thinking (cont.)
Recursive Algorithm to Search an Array
if the array is empty
return -1 as the search result
else if the middle element matches the target
return the subscript of the middle element as the result
else if the target is less than the middle element
recursively search the array elements preceding the
middle element and return the result
else
recursively search the array elements following the
middle element and return the result
Steps to Design a Recursive
Algorithm
There must be at least one case (the base case), for a
small value of n, that can be solved directly
A problem of a given size n can be reduced to one or
more smaller versions of the same problem (recursive
case(s))
Identify the base case(s) and solve it/them directly
Devise a strategy to reduce the problem to smaller
versions of itself while making progress toward the
base case
Combine the solutions to the smaller problems to solve
the larger problem
Recursive Algorithm for Finding the
Length of a String
if the string is empty (has no characters)
the length is 0
else
the length is 1 plus the length of the string that
excludes the first character
Recursive Algorithm for Finding the
Length of a String (cont.)
/** Recursive method length
@param str The string
@return The length of the string
*/
public static int length(String str) {
if (str == null || str.equals(""))
return 0;
else
return 1 + length(str.substring(1));
}
Recursive Algorithm for Printing
String Characters
/** Recursive method printChars
post: The argument string is displayed, one character
per line
@param str The string
*/
public static void printChars(String str) {
if (str == null || str.equals(""))
return;
else {
System.out.println(str.charAt(0));
printChars(str.substring(1));
}
}
Recursive Algorithm for Printing
String Characters in Reverse
/** Recursive method printCharsReverse
post: The argument string is displayed in reverse, one
character per line
@param str The string
*/
public static void printCharsReverse(String str) {
if (str == null || str.equals(""))
return;
else {
printCharsReverse(str.substring(1));
System.out.println(str.charAt(0));
}
}
Proving that a Recursive Method is
Correct
Proof by induction
Prove the theorem is true for the base case
Show that if the theorem is assumed true for n, then it
must be true for n+1
Recursive proof is similar to induction
Verify the base case is recognized and solved correctly
Verify that each recursive case makes progress towards
the base case
Verify that if all smaller problems are solved correctly,
then the original problem also is solved correctly
Tracing a Recursive Method
The process of
returning from
recursive calls and
computing the partial
results is called
unwinding the
recursion
Run-Time Stack and Activation
Frames
Java maintains a run-time stack on which it saves
new information in the form of an activation frame
The activation frame contains storage for
method arguments
local variables (if any)
the return address of the instruction that called the
method
Whenever a new method is called (recursive or
not), Java pushes a new activation frame onto the
run-time stack
Run-Time Stack and Activation
Frames (cont.)
Analogy for the Run-Time Stack for
Recursive Calls
An office tower has an employee on each level each
with the same list of instructions
The employee on the bottom level carries out part of the
instructions, calls the employee on the next level up and is
put on hold
The employee on the next level completes part of the instructions
and calls the employee on the next level up and is put on hold
The employee on the next level completes part of the instructions
and calls the employee on the next level up and is put on hold
The employee on the next level completes part of the
Inefficient
An O(n) Recursive fibonacci
Method
An O(n) Recursive fibonacci
Method (cont.)
In order to start the method executing, we provide a
non-recursive wrapper method:
/** Wrapper method for calculating Fibonacci numbers
(in RecursiveMethods.java).
pre: n >= 1
@param n The position of the desired Fibonacci
number
@return The value of the nth Fibonacci number
*/
public static int fibonacciStart(int n) {
return fibo(1, 0, n);
}
Efficiency of Recursion: O(n)
fibonacci
Efficient
Recursive Array Search
Section 5.3
Recursive Array Search
Searching an array can be accomplished using
recursion
Simplest way to search is a linear search
Examine one element at a time starting with the first
element and ending with the last
On average, (n + 1)/2 elements are examined to find
the target in a linear search
If the target is not in the list, n elements are examined
A linear search is O(n)
Recursive Array Search (cont.)
Base cases for recursive search:
Empty array, target can not be found; result is -1
First element of the array being searched = target;
result is the subscript of first element
The recursive step searches the rest of the array,
excluding the first element
Algorithm for Recursive Linear
Array Search
first = 0 last = 2
middle = 1
Binary Search Algorithm (cont.)
target
Third call
Dustin
Recursive Algorithm for n -Disk Problem: Move n Disks from the Starting Peg to the
Destination Peg
if n is 1
move disk 1 (the smallest disk) from the starting peg to the destination
peg
else
move the top n – 1 disks from the starting peg to the temporary peg
(neither starting nor destination peg)
move disk n (the disk at the bottom) from the starting peg to the
destination peg
move the top n – 1 disks from the temporary peg to the destination peg
Recursive Algorithm for Towers of
Hanoi (cont.)
Implementation of Recursive
Towers of Hanoi
Counting Cells in a Blob
Consider how we might process an image that is
presented as a two-dimensional array of color values
Information in the image may come from
an X-ray
an MRI
satellite imagery
etc.
The goal is to determine the size of any area in the
image that is considered abnormal because of its color
values
Counting Cells in a Blob – the
Problem
Given a two-dimensional grid of cells, each cell
contains either a normal background color or a
second color, which indicates the presence of an
abnormality
A blob is a collection of contiguous abnormal cells
A user will enter the x, y coordinates of a cell in the
blob, and the program will determine the count of
all cells in that blob
Counting Cells in a Blob - Analysis
Problem Inputs
the two-dimensional grid of cells
the coordinates of a cell in a blob
Problem Outputs
the count of cells in the blob
Counting Cells in a Blob -
Design
Counting Cells in a Blob - Design
(cont.)