-4

I'm trying to use recursion to find the largest number in the array, but am not getting the results i hoped. Any help would be very appreciated.

public class ArrayMax {
    public static int largestInteger(int[] array) {

        return FindlargestInteger(array, 0, -99999999);

    }   

    public static int FindlargestInteger(int[] array, int index, int max) { 

        if (index == array.length)
            return max;

        if (array[index] > max) {
            max = array[index];
        }

        FindlargestInteger(array, index + 1, max);

        return max;     
    }
}
2
  • 1
    You need to return the value of FindlargestInteger Commented Mar 21, 2016 at 22:03
  • 1
    Sidebar comment: use Integer.MIN_VALUE instead of -99999999 Commented Mar 21, 2016 at 22:04

2 Answers 2

5

You need to return a call to the function for your function to be recursive.

return FindlargestInteger(array, index + 1,max);

Code

public static int FindlargestInteger(int[] array, int index,int max){   
    if(index == array.length)
        return max;

    if (array[index] > max){
        max = array[index];
    }
    return FindlargestInteger(array, index + 1,max);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your FindlargestInteger method doesn't currently recurse. You need to first start with a base case; if you're at the end of the array return the last element; otherwise return the largest of the element at the current index or the result of recursing. And, you don't need to pass max into the function. You can do it with something like1,

public static int FindlargestInteger(int[] array, int index) {
    if (index < array.length - 1) {
        return Math.max(array[index], FindlargestInteger(array, index + 1));
    }
    return array[array.length - 1];
}

If the goal wasn't recursion, and you're using Java 8+, you might also implement it with a one line method using an IntStream like

return IntStream.of(array).max();

1Please follow Java method naming conventions, method names should start with a lower case letter. As is, your method looks like a constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.