Reputation: 1
I'm having a lot of trouble understanding how this code works. I understand basic recursion, like the factorial code, but I cannot seem to follow through this code. If someone could explain to me how to follow through this code, I would greatly appreciate it.
public class Question3 {
public static int mystery(int[] a){
return mystery(a,0);
}
public static int mystery(int [] a, int x) {
if (x == a.length-1)
return a[x];
else {
int z = mystery(a, x+1);
System.out.println(z);
if (a[x] > z)
return a[x];
else
return z;
}
}
public static void main(String[] args) {
int[] testArr = {4, 23, 5, 11, 7};
System.out.println(mystery(testArr));
}
}
Upvotes: 0
Views: 97
Reputation: 529
First of all you should notice that the array a
is neither replaced nor modified in the entire code. This means that a.length-1
will always evaluate to 4
.
The code has the following call stack:
main()
mystery(testArr)
mystery(testArr, 0)
if block: 0 != 4
mystery(testArr, 1)
if block: 1 != 4
mystery(testArr, 2)
if block: 2 != 4
mystery(testArr, 3)
if block: 3 != 4
mystery(testArr, 4)
if block: 4 == 4 // returns testArr[4]: 7
z = 7 // prints "7"
a[3]: 11 > 7 // returns testArr[3]: 11
z = 11 // prints "11"
a[2]: 5 <= 11 // returns z: 11
z = 11 // prints "11"
a[1]: 23 > 11 // returns testArr[1]: 23
z = 23 // prints "23"
a[0]: 5 <= 23 // returns 23
returns 23
prints "23"
So the mystery
goes to the end of your array and then returns from back to front the current maximum element observed so far and prints it. In the end you will get the maximum element of the whole array.
Upvotes: 1
Reputation: 714
This method is recursively checking what is the highest number, System.out.println(mystery(testArr));
will print 23
, the highest number. If you update the array with another numbers will be able to check that.
Out of clarity, you could change the mystery(int [] a, int x)
method to:
public static int mystery(int [] a, int x) {
if (x == a.length-1)
return a[x];
else {
int z = mystery(a, x+1);
System.out.println(z);
return Math.max(a[x], z);
}
}
Emphasis in return Math.max(a[x], z);
. And would be clearer what is trying to do. Picking up the higher number and recursively checking it against the next one.
Upvotes: 0