This is a homework assignment and I'm having trouble figuring out what I'm doing wrong. I am supposed to write a method that returns the max int from an array of ints without using a loop or any other methods such as Math.max etc. I wrote a method that can do it with a while loop but I am having trouble figuring out what is wrong with my recursive search. I keep getting 0 when doing the recursive search.
public class RecursiveGetMax {
public static void main(String[] args) {
int [] arr = {1,3,7,5,4};
System.out.println("The max int using a loop is: " + loopMax(arr,0));
System.out.println("The max int using a recursive search is: " + recursiveMax(arr,0));
}
public static int loopMax(int[] arr, int index) {
int ret = 0;
int maxSoFar = 0;
while (index < arr.length-1) {
if(arr[index] >= maxSoFar) {
maxSoFar = arr[index];
}
++index;
}
if (index == arr.length-1) {
ret = maxSoFar;
}
return ret;
}
public static int recursiveMax(int[]arr, int index) {
int maxSoFar = 0;
int ret = 0;
if (index > arr.length-1) {
ret = maxSoFar;
}
else {
if (arr[index] >= maxSoFar){
maxSoFar = arr[index];
}
recursiveMax(arr,index + 1);
}
return ret;
}
}