Unit 3
Recursion
King Fahd University of Petroleum & Minerals
College of Computer Science & Engineering
Information & Computer Science Department

Reading Assignment
“Data Structures and Algorithms in Java”, 3
rd
Edition, Adam Drozdek, Cengage Learning,
ISBN 978-9814239233
Chapter 5 Sections 1-8, 10.
Backtracking and the Case Study in Sections 9 and
11 are optional reading.

Objectives
Discuss the following topics:
Recursive Definitions
Method Calls and Recursion Implementation
Tracing of Recursive Methods
Tail and Non-Tail Recursive Methods
Direct and Indirect Recursive Methods
Nested and non-Nested Recursive Methods
Excessive Recursion
Final Remarks on Recursion
3

Recursive Definitions
Recursive definitions
are programming
concepts that define themselves
A recursive definition consists of two parts:
The
anchor
or
ground
case
,
the basic elements
that are the building blocks of all other elements of
the set
Rules that allow for the construction of new objects
out of basic elements or objects that have already
been constructed
4

Recursive Definitions
(continued)
Recursive definitions serve two purposes:
Generating
new elements
Testing
whether an element belongs to a set
Recursive definitions are frequently used to
define functions and sequences of numbers
5

What is a Recursive Method?
A method is recursive if it calls itself either directly or indirectly.
Recursion is a technique that allows us to break down a
problem into one or more simpler sub-problems that are similar
in form to the original problem.
Example 1: A recursive method for computing x!
This method illustrates all the important ideas of recursion:
A base (or stopping) case
Code first tests for stopping condition ( is
x = = 0 ?)
Provides a direct (non-recursive) solution for the base case (0! = 1).
The recursive case
Expresses solution to problem in 1, 2 or more smaller parts
Invokes itself to compute the smaller parts, eventually reaching the base case
long factorial (int x) {
if (x == 0)
return 1;
//base case
else
return x * factorial (x – 1);
//recursive case
}
6

What is a Recursive Method?
Example 2: count zeros in an array
int countZeros(int[] x, int index) {
if (index == 0)
return x[0] == 0 ? 1: 0;
else if (x[index] == 0)
return 1 + countZeros(x, index – 1);
else
return countZeros(x, index – 1);
}
7

Method Calls and Recursion
Implementation
When a method is called an Activation Record is created. It
contains:
The values of the parameters.
The values of the local variables.
The return address (The address of the statement after the call
statement).
The previous activation record address.
A location for the return value of the activation record.
When a method returns:
The return value of its activation record is passed to the previous
activation record or it is passed to the calling statement if there is
no previous activation record.

#### You've reached the end of your free preview.

Want to read all 39 pages?

- Winter '12
- Ghouti