Recursive Algorithms


Outline:

  1. Review PA3 model..
  2. Discuss recursion

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(s) (easy case)
The part of the definition (or method) that is not recursive.
Refinement case
The part of the method that is recursive and helps us to "approach" the base case.
Activation record (invocation record)
A record of the current method call

Recursion in Mathematics

A function is defined recursively if some value of f(n) is given (like f(0)) 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.

Designing a Recursive Method

Max - Returns the largest value from an array list of Integers.

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

Examples

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



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