合并和计数 - 堆栈溢出错误

时间:2014-02-26 18:10:34

标签: mergesort stack-overflow

我正在尝试对整数数组进行排序和计数。以下是我的代码。当我递归调用sortAndCount并且无法找出原因时,我不断收到堆栈溢出错误。有什么想法吗?

    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;

}

1 个答案:

答案 0 :(得分:0)

为了使递归停止,您需要一个基本案例/停止条件。

您当前的功能永远不会通过这一行:

inversionsLeft = sortAndCount(intLeft);

你的递归应该是这样的:

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

您收到stack overflow错误,因为您的递归函数没有停止条件,因此它会无限期地继续(直到堆栈溢出)。