[英]Stackoverflow Error while finding min and max in an array?
I am working on a problem to find Minimum and Maximum value in an array. 我正在研究一个问题,以找到数组中的最小值和最大值。 I have my below program, whenever I run it, I am seeing java.lang.StackOverflowError
: 我有我的下面的程序,每当我运行它,我看到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;
}
}
Why this error is being thrown and what does it mean? 为什么抛出这个错误是什么意思? How can I fix this? 我怎样才能解决这个问题?
You forgot the return result;
你忘记了return result;
in this piece of code: 在这段代码中:
// if there is only one element arr= {1}
if (low == high) {
result.min = arr[low];
result.max = arr[high];
return result;
}
I don't think recursion makes sense for this task. 我认为递归对于这项任务没有意义。 This code works well: 这段代码效果很好:
int a1[] = { 3, 4, 2, 6, 8, 1, 9, 12, 15, 11 };
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int a : a1) {
if (a < min) {
min = a;
}
if (a > max) {
max = a;
}
}
System.out.println("Min: " + min);
System.out.println("Max: " + max);
Unless you want to make it recursively, easiest solution is using a stream: 除非您想以递归方式进行,否则最简单的解决方案是使用流:
IntSummaryStatistics stats = Arrays.stream(a1).summaryStatistics();
int max = stats.getMax();
int min = stats.getMin();
// or:
int max = Arrays.stream(a1).max();
int min = Arrays.stream(a1).min();
Other way is using for-loop and simply checking every number: 其他方法是使用for循环并简单地检查每个数字:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i : a1) {
if (i > max) {
max = i;
}
if (i < min) {
min = i;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.