Recursive Algorithms


Terminology

Recurrence Relation
A relation between successive values of a function that allows the systematic calculation of values, given an initial value.
Recursion
Formal: Computation using a recurrence relation.
Informal: A function is recursive if it calls itself.
Base case (easy case)
The part of the definition (or method) that is not recursive.
Activation record (invocation record)
A record of the current method call

Recursion in Mathematics

A function is defined recursively if the value of f(0) is given and the value of f(n+1)is given in terms of f(n).

Factorial:

f(0) = 1

f(n + 1) = f(n) * (n+1)

Java examples

Factorial.java
FactorialDriver.java

Tracing Recursion

Activation record - maintains the current state of method execution.

Created for each invokation of a method. The current method is visible; its caller is next in the stack; its caller is next; until you reach main.

Contains

Simulating the activation record

Most easily done with "cards" or boxes on a piece of paper. For each method call, you add a new card to the top of the stack(noting on the original card your return point). The top card always represents the currently executing method.

Trace the getFactorial method for the number 5.

Designing a Recursive Method

Palindromes - Words that have the same letters from left to right or right to left.

Examples

Note - Non-letters are ignored. Case is ignored.

1. Determine the easy case (s)
2. Figure out how to transform the hard case so that it approaches the easy case.

What is our easy case?
Is there more than one?

What transformation can we do to approach the easy case?

Is there more than one way to design this?

Palindrome.java
PalindromeTester.java

What about the manipulation of the String to remove non-letters and convert to lower case?

PalindromeV2.java
PalindromeTesterV2.java

Dr. Bernstein's lecture notes for today has other examples of recursion.

NOTE: For lab on Wednesday, bring some 3x5 cards or sticky notes. Both are sold in the copy center. You may also do the tracing on paper if you prefer.



CS 239 - Spring 2006
Department of Computer Science Nancy Harris Home Page Current Classes Link