Bart g
Bart g

Reputation: 585

Recursive explanation

Today in the class of Java the professor came up with this example but I really couldn't understand very well the process how to go through this method in order to get the result = 4. Could any body please put some lines as clear as possible how is that this method is solved?? Thank you Ok so this is the method:

public static int mystery(int[] values, int start, int value)
{
    if(start == values.length) {
        return value;
    }
    else
        return Math.max(value, mystery(values, start+1, values[start]));
}

Upvotes: 2

Views: 190

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258608

The result isn't 4, but the maximum in the array.

It goes like this:

values is the array of elements.

start is the current index.

value is the current maximum.

If the current index is past the length of the array, return the current maximum. This is the first line of code and the halting condition.

Otherwise, return the maximum between the current maximum and the maximum of the array past the current index. Which will, recursively, ultimately return the maximum in the array.

You initially call this function with start = 0 and value = 0.

Assume values = [2,5,1].

mystery ( [2,5,1], 0 , 0 ) ->
  start (0) != values.length (3) ->
  return max (0, mystery( [2,5,1], 1, 2 ) ->
      mystery ( [2,5,1], 1, 2 ) ->
        start (1) != values.length ->
        return max (2, mystery( [2,5,1], 2, 5 ) ->
            mystery ([2,5,1], 2, 5) ->
            start(2) != values.length ->
                return max(5, mystery( [2,5,1], 3, 2) ->
                   start(3) == values.length ->
                   return value (1)
                -> return max(5,1)
            -> return 5
         -> return max(2,5)
       -> return 5
   -> return max(0,5)
-> return 5

Upvotes: 8

Michael Jasper
Michael Jasper

Reputation: 8058

Here is a working example that you can play with: (it is in javascript, but functions the same way)

http://jsfiddle.net/rEZ66/1/

Basically, the function mystery takes the array as input, and loops though each element return the maximum element.

When it runs, the recursive function compares the highest value it has found so far (value) to the current element of the array(values[start]), and loops again using the current largest value, against the next element start+1

Upvotes: 1

Related Questions