所以我正在研究这个问题,要求我使用递归来创建一个方法,使用此标头“private static int findLargest (int [] items, int first, int) 返回整数数组中最大元素的索引最后的)”。这是我写的,虽然它确实按预期工作,但如果我向它提供一个大于 5 个元素的数组,它会给出 StackOverflowError。
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
您没有正确划分给定范围。
更改此:
int firstHalf = findLargest (items, first, last / 2);
int secondHalf = findLargest(items, last / 2 + 1, last);
对此:
int mid = (first + last) / 2;
int firstHalf = findLargest (items, first, mid);
int secondHalf = findLargest(items, mid + 1, last);