Stackoverflow Error while searching min and max in an array?
I am working on the problem of finding the minimum and maximum values in an array. I have my below program, whenever I run it I see 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 is this error occurring and what does it mean? How can I fix this?
+3
source to share
3 answers
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);
+2
source to share
If you want to do it recursively the easiest is to use 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();
Another way is to use a for-loop and just check each number:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i : a1) {
if (i > max) {
max = i;
}
if (i < min) {
min = i;
}
}
+1
source to share