CMPT 126: Lecture 10
Recursion
Tamara Smyth, [email protected]
School of Computing Science,
Simon Fraser University
October 25, 2007
1
Recursion
•
Recursion is the process of deFning something in
terms of itself.
•
Andrew Plotkin (interactive Fction writer, aka Zarf)
said:
“If you already know what recursion is, just
remember the answer. Otherwise, Fnd someone
who is standing closer to Douglas Hofstadter
than you are; then ask him or her what
recursion is.”
•
Consider the following ‘dictionary’ deFnitions:
recursion:
See “recursion”.
decoration:
n. any ornament or adornment
used to decorate something.
•
Though such recursive deFnitions are not always
helpful when used in the dictionary, they can be very
useful when representing and/or solving mathematical
or computer programming problems.
CMPT 126: Recursion, Lecture 10
2
Thinking Recursively
•
To program recursively, we must learn to
think
recursively.
•
Consider the following deFnition of a
List
:
“a list is one or more numbers separated by commas”.
•
An alternate, equivalent
recursive
deFnition is:
A
List
is a: number
or a: number comma
List
•
The recursive deFnition deFnes each of the following
lists:
–
24, 45, 9
–
2, 56
–
34, 45, 3, 7, 76, 94, 54, 1
–
20
•
The last of list containing a single element is
described by the nonrecursive part of the deFnition,
that is, the base case.
CMPT 126: Recursion, Lecture 10
3
Tracing the Recursive Defnition oF
List
37
LIST
LIST
comma
number
comma
LIST
number
LIST
number
comma
number
24, 88, 40, 37
88, 40, 37
24
,
88
,
40, 37
40
,
37
Figure 1: Tracing through a recursive
List
.
•
Note the deFnition of
List
contains one option that is
recursive and one that is not.
•
The nonrecursive part is called the
base case
.
•
Without a
base case
, the recursion would never end, a
problem referred to as
infnite recursion
.
CMPT 126: Recursion, Lecture 10
4
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentRecursion in Math
•
Consider the
factorial
function,
N
!
, deFned as the
product of all integers between 1 and
N
.
3! = 3
×
2
×
1 = 6
N
! =
N
×
(
N

1)
×
(
N

2)
×
.. .
×
1
•
What is the base case? Look for the case that’s not
deFned in terms of
N
: eg.
1! = 1
or
0! = 1
.
•
What is the recursive case? DeFne the problem in
terms of itself, while reducing the problem size (i.e.,
reduce
N
!
to
(
N

1)!
)
•
The factorial function can be expressed recursively as
1! = 1
(
base case
)
N
! =
N
×
(
N

1)!
for
N >
1
(
recursive case
)
•
The base case is 1!. All other values of
N
!
are deFned
recursively as
N
×
(
N

1)!
CMPT 126: Recursion, Lecture 10
5
Recursive Factorial Function
•
Given here in pseudocode:
function factorial(n)
{
if (n<=1)
return 1;
else
return n * factorial(n1);
}
•
Eventually the base case will be reached:
4! = 4
×
3!
= 4
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '08
 DIANA
 Recursion, Hanoi

Click to edit the document details