Monday, September 13, 2010

A classic recursive algorithm

Here is a classic recursive algorithm.  The mathematical formula for factorial:
  * 1!=1
  * 2!=2 (2*1)
  * 3!=6 (3*2*1)
  * 4!=24 (4*3*2*1)
  * 5!=120 (5*4*3*2*1)
  * and so on

This can be described in pseudo-code as:
fact(x) ::= if ( x == 1 ) then 1 else x + fact(x-1)

In Java code it would look like this:

1    public int fact(int x) {
2        if ( x== 1 )
3            return 1;
4        else
5            return x * fact(x-1);
6    }

It is recursive because the function has a call to itself (see line 5).  The most important part of creating a recursive algorithm is to determine the halt condition.  In the case of the fact function the halt condition is when x==1.  If you fail to code a halt condition (or if the condition has a bug) then you will likely run into a infinite loop which in Java would result in a StackOverflowError.