Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor this recursive method?

Tags:

java

recursion

I'm pretty new to the idea of recursion and this is actually my first attempt at writing a recursive method.

I tried to implement a recursive function Max that passes an array, along with a variable that holds the array's size in order to print the largest element.

It works, but it just doesn't feel right!

I have also noticed that I seem to use the static modifier much more than my classmates in general...

Can anybody please provide any general tips as well as feedback as to how I can improve my code?

public class RecursiveTry{

static int[] n = new int[] {1,2,4,3,3,32,100};
static int current = 0;
static int maxValue = 0;
static int SIZE = n.length;

public static void main(String[] args){
    System.out.println(Max(n, SIZE));
}   

public static int Max(int[] n, int SIZE) {
    if(current <= SIZE - 1){
        if (maxValue <= n[current]) {
            maxValue = n[current];
            current++;
            Max(n, SIZE);                       
        }
        else {
            current++;
            Max(n, SIZE);
        }
    }
    return maxValue;
}

}

like image 938
101010110101 Avatar asked Oct 29 '08 01:10

101010110101


People also ask

How do you get rid of a recursive function?

A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case. A base case is a case, where the problem can be solved without further recursion.

What is recursive method in Javascript?

Recursion is when a function calls itself until someone stops it. It can be used instead of a loop. If no one stops it, it'll recurse forever and crash your program. A base case is a condition that stops the recursion.

How do you stop a recursion in Java?

The best way to get out of a recursive loop when an error is encountered is to throw a runtime exception.


2 Answers

Your use of static variables for holding state outside the function will be a source of difficulty.

An example of a recursive implementation of a max() function in pseudocode might be:

function Max(data, size) {
    assert(size > 0)
    if (size == 1) {
        return data[0]
    }
    maxtail = Max(data[1..size], size-1)
    if (data[0] > maxtail) {
        return data[0]
    } else {
        return maxtail
    }
}

The key here is the recursive call to Max(), where you pass everything except the first element, and one less than the size. The general idea is this function says "the maximum value in this data is either the first element, or the maximum of the values in the rest of the array, whichever is larger".

This implementation requires no static data outside the function definition.

One of the hallmarks of recursive implementations is a so-called "termination condition" which prevents the recursion from going on forever (or, until you get a stack overflow). In the above case, the test for size == 1 is the termination condition.

like image 109
Greg Hewgill Avatar answered Nov 15 '22 10:11

Greg Hewgill


Making your function dependent on static variables is not a good idea. Here is possible implementation of recursive Max function:

int Max(int[] array, int currentPos, int maxValue) {
    // Ouch!
    if (currentPos < 0) {
        raise some error
    }
    // We reached the end of the array, return latest maxValue
    if (currentPos >= array.length) {
        return maxValue;
    }
    // Is current value greater then latest maxValue ?
    int currentValue = array[currentPos];
    if (currentValue > maxValue) {
        // currentValue is a new maxValue
        return Max(array, currentPos + 1, currentValue);
    } else {
        // maxValue is still a max value
        return Max(array, currentPos + 1, maxValue);
    }
}
...

int[] array = new int[] {...};
int currentPos = 0;
int maxValue = array[currentPos] or minimum int value;  
    maxValue = Max(array, currentPos, maxValue);
like image 23
aku Avatar answered Nov 15 '22 10:11

aku