Java MergeSort实现提供了StackOverflow

Java MergeSort实现提供了StackOverflow,java,stack-overflow,mergesort,Java,Stack Overflow,Mergesort,我一直在尝试实现一个MergeSort,它将数组分成三个部分,而不是两个部分。我似乎在某个地方遇到了堆栈溢出异常。有人能帮我找到它吗?(第54、58、59行报告了SOs) 导入java.util。; 导入java.io 类MergeSortQuestion{ // merges sorted subarrays A[start...firstThird], A[firstThird+1,secondThird], and A[secondThird+1,stop] public static v

我一直在尝试实现一个MergeSort,它将数组分成三个部分,而不是两个部分。我似乎在某个地方遇到了堆栈溢出异常。有人能帮我找到它吗?(第54、58、59行报告了SOs)

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

类MergeSortQuestion{

// 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]+" ");
}
}
//合并已排序的子数组A[start…firstThird]、[firstThird+1,secondThird]和[secondThird+1,stop]
公共静态无效合并三向(int A[],int start,int firstThird,int secondThird,int stop)
{
int indexLeft=启动;
int indexFirstThird=firstThird+1;
int index secondThird=secondThird+1;
int tmp1[]=新的int[A.length];
int tmpIndex=开始;

而(tmpIndex您的
firstThird
secondThird
变量不会在
mergesortthway
执行过程中的某个特定点从一个迭代到另一个迭代改变值。 以你为例,我得到:

start=4 stop=6
firstThird=3 secondThird=6
start=4 stop=6
firstThird=3 secondThird=6
// so java.lang.StackOverflowError
计算
firstThird
secondThird
的公式似乎不起作用。请尝试使用

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

看起来您的递归方法没有停止。请进行一些调试以找出原因。在
mergesorttthreeway
中,您可能希望执行一些操作来
启动
停止