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]));
}
The result isn’t 4, but the maximum in the array.
It goes like this:
valuesis the array of elements.startis the current index.valueis 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 = 0andvalue = 0.Assume
values = [2,5,1].