0

Can someone please tell me what I am doing wrong? I have coded this min and max finder but I keep getting this error: "StackOverflowError" at my "mml = getMinMax(a, low, high)". Any help would be greatly appreciated. Thank you!

public class MinMax {
int min;
int max;

public static void main(String[] args){

    int a[] = {4, 23, 6, 42, 11};
    int aSize = a.length -1;
    MinMax test = getMinMax(a,0,aSize);
    System.out.println("Minimum: " + test.min);
}


public static MinMax getMinMax(int a[], int low, int high){
    MinMax minmax = new MinMax();
    MinMax mml = new MinMax();
    MinMax mmr = new MinMax();

    int mid = ((low + high)/2);
    mml = getMinMax(a, low, mid);
    mmr = getMinMax(a, mid+1, high);

    if(mml.min < mmr.min){
        minmax.min = mml.min;
    }else{
        minmax.max = mmr.max;
    }

    if(mml.max > mmr.max){
        minmax.max = mml.max;
    }else{
        minmax.max = mmr.max;
    }
    return minmax;      
}   

}

MostPalone
  • 77
  • 7
  • 1
    You are recursively calling the getMinMax function but you don't ever terminate the recursion with a base case. – David Choweller Feb 09 '17 at 00:39
  • I'm not sure why you're initializing the class `MinMax`, since it doesn't appear to do anything. Anyways, that error means you're recursing too many time. Your function recurses twice per call, and doesn't have a base case, so it basically becomes an infinite loop. You need to lookup how to use recursion properly. – Carcigenicate Feb 09 '17 at 00:39

0 Answers0