Search code examples
mergesortstack-overflow

Merge and Count - Stack Overflow Error


I'm trying to sort and count inversions for an array of integers. Below is my code. I keep getting a stack overflow error though when I recursively call sortAndCount and can't figure out why. Any ideas?

    private static int sortAndCount(int intToSort[]){

    int inversionsLeft;
    int inversionsRight;
    int inversionsMerged;

    int m = intToSort.length/2;

    int[] intLeft = new int[m];
    int[] intRight = new int[intToSort.length-m];

    for (int i=0; i < m; i++){
        intLeft[i] = intToSort[i];
    }

    for (int i = 0;i < intRight.length; i++){
            intRight[i] = intToSort[m+i];
    }

    inversionsLeft = sortAndCount(intLeft);
    inversionsRight = sortAndCount(intRight);

    sorted = new int[intToSort.length];
    inversionsMerged = mergeAndCount(intLeft, intRight);

    return(inversionsLeft + inversionsRight + inversionsMerged);

}

private static int mergeAndCount(int[] intLeft, int[] intRight){

    int count = 0;
    int i = 0;
    int j = 0;
    int k = 0;

    while(i < intLeft.length && j < intRight.length){

        if(intLeft[i] < intRight[j]){
            sorted[k] = intLeft[i];
            i++;
        }

        else{
            sorted[k] = intRight[j];
            count += intLeft.length - i + 1;
            j++;
        }

        k++;

    }

     while (i < intLeft.length)
        {
            sorted[k++] = intLeft[i++];
        }

     while (j < intRight.length)
        {
            sorted[k++] = intRight[j++];
        }

     return count;

}

Solution

  • In order for the recursion to stop, you need a base case / stopping condition.

    Your current function will NEVER get passed this line:

    inversionsLeft = sortAndCount(intLeft);
    

    Your recursion should work something like this:

    if (simple case) {
       // stopping condition
    }
    else {
       // recursive call
    }
    

    You're getting a stack overflow error because your recursive function has no stopping condition, so it's continuing indefinitely (until the stack overflows).