-1

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;
}
}
  • Please follow up link > http://stackoverflow.com/questions/19590242/finding-max-value-in-an-array-using-recursion – Rahul Patel Dec 08 '16 at 06:17
  • Possible duplicate of [What is a debugger and how can it help me diagnose problems?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Dec 08 '16 at 08:05

2 Answers2

0

try this code The main problem was then maxSoFar was getting overwritten and your recursive call did not return its value

static int maxSoFar = Integer.MIN_VALUE;  // set to a very small number
public static void main (String [] args) throws Exception 
{
    int [] arr = {1,3,7,5,4};

    System.out.println("The max int using a recursive search is: " + recursiveMax(arr,0));  // pass it in

}

public static int recursiveMax(int[]arr, int index) {  

    if (index > arr.length-1) {
        return maxSoFar;
    }
    else {
        if (arr[index] >= maxSoFar){
            maxSoFar = arr[index];
        }
        return recursiveMax(arr,index + 1);
    }
}

Edit

Changed to use static variable due to OP's comments

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

look at the max function..

public class Snippet {
    public static void main(String[] args) {
        int arr[] = {3,5,6,2,8,6,5,1};
        System.out.println(max(arr, 1, arr[0]));
    }

    public static int max(int arr[], int i, int max){
        if(i < arr.length){
            max = Math.max(arr[i], max);
            return max(arr, i+1, max);
        }
        return max;
    }
}

the key point is you need to carry all require data, while recurse

subash
  • 3,116
  • 3
  • 18
  • 22