java - 归并排序实现给出了 StackOverflow

标签 java stack-overflow mergesort

我一直在尝试实现一个合并排序,将数组分为三个部分而不是两个部分。我似乎在某个地方遇到了 StackOverflow 异常。有人可以帮我找到它吗? (SO 在第 54、58、59 行报告)

导入java.util.; 导入java.io。;

类合并排序问题{

// merges sorted subarrays A[start...firstThird], A[firstThird+1,secondThird], and A[secondThird+1,stop]
public static void mergeThreeWay(int A[], int start, int firstThird, int secondThird, int stop) 
{

    int indexLeft = start;
    int indexFirstThird = firstThird+1;
    int indexSecondThird = secondThird+1;
    int tmp1[] = new int[A.length];
    int tmpIndex = start;
    while(tmpIndex <= firstThird){

        if (indexFirstThird < firstThird || (indexLeft <= firstThird && A[indexLeft] <= A[indexFirstThird])){

            tmp1[tmpIndex] = A[indexLeft];
            indexLeft++;

        }else if(indexSecondThird < secondThird || (indexFirstThird <= secondThird && A[firstThird] <= A[indexSecondThird])){

            tmp1[tmpIndex] = A[indexFirstThird];
            indexFirstThird++;

        }else{

            tmp1[tmpIndex] = A[indexSecondThird];
            indexSecondThird = indexSecondThird + 1;

        }

        tmpIndex++;
    }

    int i = 0;

    for(int temp : tmp1){
        A[i] = temp;
        i++;
    }



}



// sorts A[start...stop]
public static void mergeSortThreeWay(int A[], int start, int stop) {

    if (start < stop){

        int firstThird = (start+stop)/3;
        int secondThird = 2*(firstThird);
        mergeSortThreeWay(A, start, firstThird);
        mergeSortThreeWay(A, firstThird+1, secondThird);
        mergeSortThreeWay(A, secondThird+1, stop);
        mergeThreeWay(A, start, firstThird, secondThird, stop);
    }


}


public static void main (String args[]) throws Exception {

int myArray[] = {8,3,5,7,9,2,3,5,5,6}; 

mergeSortThreeWay(myArray,0,myArray.length-1);

System.out.println("Sorted array is:\n");
for (int i=0;i<myArray.length;i++) {
    System.out.println(myArray[i]+" ");
}
}

}

最佳答案

您的 firstThirdsecondThird 变量在 mergeSortThreeWay 执行中的某个点不会将值从一次迭代更改为另一次迭代。 在你的例子中,我得到:

start=4 stop=6
firstThird=3 secondThird=6
start=4 stop=6
firstThird=3 secondThird=6
// so java.lang.StackOverflowError

计算 firstThirdsecondThird 的公式似乎不起作用。尝试使用

firstThird = (stop-start)/3 + start;
secondThird = 2*(stop-start)/3 + start;

关于java - 归并排序实现给出了 StackOverflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19044357/

相关文章:

java - QGraphicsScene 像素图 GridView

java - Cassandra-CQL ClusterBuilder 的 addContactPoints 的工作

Function0 上的 Scala 堆栈修改

c++ - 我的代码泄漏了。我该如何解决?

java - 在 hackerrank 中为相同的测试用例获取不同的输出

Java 返回错误的图像类型

java - 执行外部排序时出现 StackOverflowError

java - 通用可比较合并排序算法的 Stackoverflow 错误

c++ - 合并排序 - 仅对 2^n 个元素进行排序

java - 了解合并排序的工作原理