tags:

views:

1080

answers:

12

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;
}

}

+3  A: 

A "max" function is the wrong type of thing to write a recursive function for -- and the fact you're using static values for "current" and "maxValue" makes your function not really a recursive function.

Why not do something a little more amenable to a recursive algorithm, like factorial?

XPav
Note also that it depends on the language - in Haskell for example it is perfectly reasonable to implement a max function recursively.
Jamie Love
If you can define a recurrence relation you can implement a recursive solution. A recursive max function is perfectly cromulent.
Bill the Lizard
+6  A: 

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.

Greg Hewgill
I was about to write something similar, too slow! vpotok, the static modifier is generally used for defining constants.
Feet
A: 

First, let's take care of the static scope issue ... Your class is defining an object, but never actually instantiating one. Since main is statically scoped, the first thing to do is get an object, then execute it's methods like this:

public class RecursiveTry{

    private int[] n = {1,2,4,3,3,32,100};

    public static void main(String[] args){
        RecursiveTry maxObject = new RecursiveTry();
        System.out.println(maxObject.Max(maxObject.n, 0));
    }

    public int Max(int[] n, int start) {
        if(start == n.length - 1) {
         return n[start];
        } else { 
         int maxRest = Max(n, start + 1);
         if(n[start] > maxRest) {
             return n[start];
         }
         return maxRest;
        }
    }

}

So now we have a RecursiveTry object named maxObject that does not require the static scope. I'm not sure that finding a maximum is effective using recursion as the number of iterations in the traditional looping method is roughly equivalent, but the amount of stack used is larger using recursion. But for this example, I'd pare it down a lot.

One of the advantages of recursion is that your state doesn't generally need to be persisted during the repeated tests like it does in iteration. Here, I've conceded to the use of a variable to hold the starting point, because it's less CPU intensive that passing a new int[] that contains all the items except for the first one.

Steve Moyer
Max maxObject = new Max(); ?? There is no Max class, just a function...
TheSoftwareJedi
Agreed. He doesn't really need an object, unless you're trying to have some sort of templated function that takes a generic object and finds its max. I think for this implementation using integers is just fine.
SauceMaster
Yeah ... just stuck it in my IDE and it bombed horribly ... I'm fixing it up now!
Steve Moyer
Okay ... there's a running example!
Steve Moyer
A: 

You are essentially writing an iterative version but using tail recursion for the looping. Also, by making so many variables static, you are essentially using global variables instead of objects. Here is an attempt at something closer to a typical recursive implementation. Of course, in real life if you were using a language like Java that doesn't optimize tail calls, you would implement a "Max" function using a loop.

public class RecursiveTry{
  static int[] n;

  public static void main(String[] args){
        RecursiveTry t = new RecursiveTry(new int[] {1,2,4,3,3,32,100});
        System.out.println(t.Max());
  }       

  RecursiveTry(int[] arg) {
    n = arg;
  }

  public int Max() {
    return MaxHelper(0);
  }

  private int MaxHelper(int index) {
    if(index == n.length-1) {
      return n[index];
    } else {
      int maxrest = MaxHelper(index+1);
      int current = n[index];
      if(current > maxrest)
        return current;
      else
        return maxrest;
    }
  }
}
Glomek
+2  A: 

"not-homework"?

Anyway. First things first. The

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

have nothing to do with the parameters of Max() with which they share their names. Move these over to main and lose the "static" specifiers. They are used only once, when calling the first instance of Max() from inside main(). Their scope shouldn't extend beyond main().

There is no reason for all invocations of Max() to share a single "current" index. "current" should be local to Max(). But then how would successive recurrences of Max() know what value of "current" to use? (Hint: Max() is already passing other Max()'s lower down the line some data. Add "current" to this data.)

The same thing goes for maxValue, though the situation here is a bit more complex. Not only do you need to pass a current "maxValue" down the line, but when the recursion finishes, you have to pass it back up all the way to the first Max() function, which will return it to main(). You may need to look at some other examples of recursion and spend some time with this one.

Finally, Max() itself is static. Once you've eliminated the need to refer to external data (the static variables) however; it doesn't really matter. It just means that you can call Max() without having to instantiate an object.

aib
+4  A: 

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);
aku
I'd suggest a small change, as long as we're being verbose? Why don't you merge and move the "return Max(...)" lines out of the conditional, and use a new variable such as "newMaxValue" as the third parameter? (And decide its value in the if/else blocks, of course.)
aib
Note that aku is passing the partial calculation (the maxValue) on the stack rather than using even an _instance_ variable. +1 in keeping with the "spirit" of recursion. (It's also a tiny bit easier to parallelize in C# or Java. Not that you'd parallelize this tiny program!)
Larry OBrien
aib, currentValue variable is just for readability, i.e. I wanted to add comments. I feel there is no need for newMaxValue in this case
aku
Now that I've looked at it again, it doesn't seem that verbose. It must've been the Properly Capitalized comments that threw me off :). Yeah, let it keep its spirit.
aib
+2  A: 

As others have observed, there is no need for recursion to implement a Max function, but it can be instructive to use a familiar algorithm to experiment with a new concept. So, here is the simplified code, with an explanation below:

public class RecursiveTry
{
    public static void main(String[] args)
    {
        System.out.println(Max(new int[] {1,2,4,3,3,32,100}, 0, 0));
    }   

    public static int Max(int[] n, int current, int maxValue) 
    {
        if(current < n.Length)
        {
            if (maxValue <= n[current] || current == 0))
            {
                return Max(n, current+1, n[current]);
            }
            return Max(n, current+1, maxValue);
        }
        return maxValue;
   }
}

all of the static state is gone as unnecessary; instead everything is passed on the stack. the internal logic of the Max function is streamlined, and we recurse in two different ways just for fun

Steven A. Lowe
Show me a recursive function that *can't* be refactored into an iterative solution.
paxdiablo
@[Pax Diablo]: they are theoretically equivalent; for something this simple, iteration is preferred (more efficient, less code, easier to understand, less stack usage, etc.)
Steven A. Lowe
@Pax: How about qicksort? How do you implement that using iteration?
DasBoot
@[DasBoot]: in general, you keep everything that would be on the stack in a queue, and manage the queue yourself
Steven A. Lowe
A: 

You are indeed overusing static. You don't really need so many global variables, either. Try moving

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;

into your main() function so that they are local variables.

public static void main(String[] args)
{
  int[] n = new int[] {1,2,4,3,3,32,100};
  int current = 0;
  int maxValue = 0;
  int SIZE = n.length;
  ...other code

}

Not a solution to your main question, but its good practice to use local variables over global ones (in general)

---As I finish this, I realize that I'm just actuating what aib said above

SauceMaster
A: 

In Scheme this can be written very concisely:

(define (max l)
    (if (= (length l) 1)
        (first l)
        (local ([define maxRest (max (rest l))])
          (if (> (first l) maxRest)
              (first l)
              maxRest))))

Granted, this uses linked lists and not arrays, which is why I didn't pass it a size element, but I feel this distills the problem to its essence. This is the pseudocode definition:

define max of a list as:
    if the list has one element, return that element
    otherwise, the max of the list will be the max between the first element and the max of the rest of the list
Claudiu
I'm sure it could be written concisely in Perl as well but would anyone be able to read it? :-)
paxdiablo
A: 

Here's a Java version for you.

public class Recursion {

    public static void main(String[] args) {
        int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        System.out.println("Max: " + max(0, data));
    }

    public static int max(int i, int[] arr) {
        if(i == arr.length-1) {
            return arr[i];
        }

        int memo = max(i+1, arr);
        if(arr[i] > memo) {
            return arr[i];
        }
        return memo;
    }
}

The recurrence relation is that the maximum element of an array is either the first element, or the maximum of the rest of the array. The stop condition is reached when you reach the end of the array. Note the use of memoization to reduce the recursive calls (roughly) in half.

Bill the Lizard
A: 

A nicer way of getting the max value of an array recursively would be to implement quicksort (which is a nice, recursive sorting algorithm), and then just return the first value.

Here is some Java code for quicksort.

RodeoClown
Isn't quicksort o(n log n)? The recursive/iterative solutions are o(n) which is better since there's no need to end up with a sorted list. You *could* also write every integer to a file named after the integer (eg 7 goes to xxx00007.txt) and then do a findfirst - this'll work but it's rubbish.
paxdiablo
A: 

Smallest codesize I could get:

public class RecursiveTry {
    public static void main(String[] args) {
        int[] x = new int[] {1,2,4,3,3,32,100};
        System.out.println(Max(x, 0));
    }   

    public static int Max(int[] arr, int currPos) {
        if (arr.length == 0) return -1;
        if (currPos == arr.length) return arr[0];
        int len = Max (arr, currPos + 1);
        if (len < arr[currPos]) return arr[currPos];
        return len;
    }
}

A few things:

1/ If the array is zero-size, it returns a max of -1 (you could have another marker value, say, -MAX_INT, or throw an exception). I've made the assumption for code clarity here to assume all values are zero or more. Otherwise I would have peppered the code with all sorts of unnecessary stuff (in regards to answering the question).

2/ Most recursions are 'cleaner' in my opinion if the terminating case is no-data rather than last-data, hence I return a value guaranteed to be less than or equal to the max when we've finished the array. Others may differ in their opinion but it wouldn't be the first or last time that they've been wrong :-).

3/ The recursive call just gets the max of the rest of the list and compares it to the current element, returning the maximum of the two.

4/ The 'ideal' solution would have been to pass a modified array on each recursive call so that you're only comparing the first element with the rest of the list, removing the need for currPos. But that would have been inefficient and would have bought down the wrath of SO.

5/ This may not necessarily be the best solution. It may be that by gray matter has been compromised from too much use of LISP with its CAR, CDR and those interminable parentheses.

paxdiablo