So I’m working on this question that’s ask me to use recursion to make a method that returns the index of the largest element in an array of ints using this header “private static int findLargest (int [] items, int first, int last)”. This is what I wrote and while it does works as intended it gives a StackOverflowError if I feed it an array higher then 5 elements.
private static int findLargest (int [] items, int first, int last) {
if (first == last) {
return first;
}//end if
if (last - 1 == first) {
if (items[first] > items[last]) {
return first;
} else {
return last;
}//end if
}//end if
int firstHalf = findLargest (items, first, last / 2);
int secondHalf = findLargest(items, last / 2 + 1, last);
if (items[firstHalf] > items[secondHalf]) {
return firstHalf;
} else {
return secondHalf;
}//end if
}//end method findLargest
You are not dividing the given range correctly with last / 2
, which may lead to last
getting a value that is less than first
, and this leads to infinite recursion.
Change this:
int firstHalf = findLargest (items, first, last / 2);
int secondHalf = findLargest(items, last / 2 + 1, last);
to this:
int mid = (first + last) / 2;
int firstHalf = findLargest (items, first, mid);
int secondHalf = findLargest(items, mid + 1, last);