我一直在尝试实现将数组分成三个部分而不是两个部分的 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]+" ");
}
}
}