Search code examples
javastack-overflowmergesort

Getting StackOverflowError when running my Merge Sort function (Java)


I am trying to implement a merge sort function, and am receiving a StackOverflowError exception when trying to run it. I saw another question similar to mine, with the answer about changing how the midpoint is calculated. I tried to change the midpoint, but am still getting the same stackoverflow error.

Thanks for looking.

public static void mergeSort(int [] arr, int low, int high) {

        if (low < high) {
            int mid = (low + high)/2;

            mergeSort(arr, low, mid + 1);
            mergeSort(arr, mid, high);          
            merge(arr, low, mid, high);
        }
    }

    public static void merge(int [] arr, int low, int mid, int high) {

        int n1 = mid - low + 1;
        int n2 = high - mid;

        int [] leftArr = new int[n1];
        int [] rightArr = new int[n2];

        for (int i = 0; i < n1; i++) leftArr[i] = arr[low + i];
        for (int j = 0; j < n2; j++) rightArr[j] = arr[mid + j + 1];

        int i = 0;
        int j = 0;

        int k = 1;

        while (i < n1 && j < n2) {
            if (leftArr[i] < rightArr[j]) {
                arr[k] = leftArr[i++];
            }
            else {
                arr[k] = rightArr[j++];
            }
            k++;
        }
        while (i < n1) arr[k++] = leftArr[i++];
        while (j < n2) arr[k++] = rightArr[j++];
    }

Solution

  • You implemented your mergesort function wrong.it should look like this

    if (low < high) {
            int mid = (low + high)/2;
    
            mergeSort(arr, low, mid -1);
            mergeSort(arr, mid, high);          
            merge(arr, low, mid, high);
        }
    

    And in the merge function you have initialised

    k=1;
    

    but it should be

    k=low;
    

    because if you will initialise k=1 everytime then it will override the array elements.