miércoles, 18 abril 2007

Java recursive functions explained // Using recursion to sum an array of numbers

« Displaying a jTable inside another jTable // JTable cellRenderer | Main | Numbers to Strings with custom symbols // DecimalFormat - DecimalFormatSymbols »

Java is a very powerful object oriented language. If you search for recursion in wikipedia you will find this definition "Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition." This means, that the function will call itself again and again until it gets the correct answer.

There are many pages where you can find great explanations to recursion theory. Most of them use the example of the Towers of Hanoi:

What I'm going to show you is an easy way to sum arrays of numbers. This example lets you see how easy can recursion be and how useful it is.

public class recursive {
    public recursive() {
                /** We create the array of numbers we want to sum
                    It can be any subclass of java.lang.Number*/
                Double[] test = {100d, 0.05d, 88d, 99d, 0.05d, 88d, 99d, 0.05d, 88d, 99d};
                /* We call our function */
                System.out.println(sum(test));
    }
    /* This is the initial function, it calculates the starting fields and results
     *automatically*/
    public Number sum(Number[] numbers){
        return sum(numbers[numbers.length - 1], numbers, numbers.length - 2);
    }
    /* This is our RECURSIVE FUNCTION */
    public Number sum(Number initialValue, Number[] numbers, int location){ 
        /* If we've reached the end of the array we return the final RESULT */
        if(location < 0){
            return initialValue;
        }
        /* Or else we are recursive */
        else{
            /*First we cast the java.lang.Number to its subclass so we can do the 
             *sum */
            if(numbers instanceof BigInteger[]){
                return sum(
                        ((BigInteger)initialValue).add((BigInteger)numbers[location]),
                        numbers,
                        (location - 1) );
            }
            else if(numbers instanceof  BigDecimal[]){
                return sum(
                        ((BigDecimal)initialValue).add((BigDecimal)numbers[location]),
                        numbers,
                        (location - 1) );
            }
            else if(numbers instanceof  Byte[]){
                return sum(
                        ((Byte)initialValue) + (Byte)numbers[location],
                        numbers,
                        (location - 1) );
            }
            else if(numbers instanceof  Double[]){
                return sum(
                        ((Double)initialValue) + ((Double)numbers[location]),
                        numbers,
                        (location - 1) );
            }
            else if(numbers instanceof  Integer[]){
                return sum(
                        ((Integer)initialValue)+ ((Integer)numbers[location]),
                        numbers,
                        (location - 1) );
            }
            else if(numbers instanceof  Long[]){
                return sum(
                        ((Long)initialValue)+ ((Long)numbers[location]),
                        numbers,
                        (location - 1) );
            }
            else if(numbers instanceof  Short[]){
                return sum(
                        ((Short)initialValue)+ ((Short)numbers[location]),
                        numbers,
                        (location - 1) );
            }
            else{
                return sum(
                        ((Float)initialValue)+ ((Float)numbers[location]),
                        numbers,
                        (location - 1) );
            }
        }   
    }
    /* THis is our main method */
    public static void main(String[] args) {
        new recursive();      
    }
}

Technorati Tags:

Posted by admin at 10:10 AM in Java

 

[Trackback URL for this entry]

Comment: Peter Veentjer at jue, 19 abr 7:45 AM

The problem with recursive calls in Java is that Java doesn't do much 'tail call optimization'. The consequence is that for each call you need another stackframe, and this will lead to problems (stack overflow and performance).

Functional programming languages like Haskell or Erlang do provide tail call optimization and in these languages a recursive call is just as expensive as an iteration.

Comment: Marc Nuri at jue, 19 abr 8:13 AM

What you say is completely true. Although recursion is an elegant method for iteration, it can lead to stack overflow in many ocasions.
You can read more about this issue at IBM: Diagnosing java code...

Your comment:

(not displayed)
 

SCode

Please enter the code as seen in the image above to post your comment.

 
 

Live Comment Preview:

 
Google
 
« April »
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
2930