我正在研究在数组中查找最小值和最大值的问题。我有下面的程序,每当我运行它时,我都会看到java.lang.StackOverflowError
:
public class MinMaxInArray {
public static void main(String[] args) {
int a1[] = { 3, 4, 2, 6, 8, 1, 9, 12, 15, 11 };
Pair result = getMinMax(a1, 0, a1.length - 1);
System.out.println("Min: " + result.min);
System.out.println("Max: " + result.max);
}
public static Pair getMinMax(int[] arr, int low, int high) {
Pair result = new Pair();
Pair left = new Pair();
Pair right = new Pair();
// if there is only one element arr= {1}
if (low == high) {
result.min = arr[low];
result.max = arr[high];
}
// if there are two element arr={1,2}
if (high == low + 1) {
if (arr[low] > arr[high]) {
result.max = arr[low];
result.min = arr[high];
} else {
result.max = arr[high];
result.min = arr[low];
}
return result;
}
// if there are more than 2 elements
int mid = (low + high) / 2;
left = getMinMax(arr, low, mid);
right = getMinMax(arr, mid + 1, high);
if (left.min < right.min) {
result.min = left.min;
} else {
result.min = right.min;
}
if (left.max > right.max) {
result.max = left.max;
} else {
result.max = right.max;
}
return result;
}
static class Pair {
int min;
int max;
}
}
为什么会引发此错误,这是什么意思?我怎样才能解决这个问题?
您return result;
在这段代码中忘记了:
// if there is only one element arr= {1}
if (low == high) {
result.min = arr[low];
result.max = arr[high];
return result;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句