When executing this recursive code, which consists of finding the position of the maximum of an array of integers, when it returns back ("returning to the previous call"), the value found changes.
How can I fix it, or where is my mistake?
public static int findMax(int[] array, int start, int end, int index) {
int max = array[index];
if (start <= end) {
if (max < array[start]) {
findMax(array, start + 1, end, start);
} else {
findMax(array, start + 1, end, index);
}
}
return index;
}
In all cases you return the value of
index
as the result of the functionfindMax
. However, when the maximum must be computed recursively, you don't store the computed value in any variable, and you should store it inindex
, or directly return it via a statementreturn
.