我在Java中创建了一个自上而下的Mergesort实现,但是它给出了StackOverFlow错误,我无法调试。任何线索?
/**
* Merge Sort
*
* Implementation in based on the concepts according to CLRS
*/
import java.util.Arrays;
import java.io.*;
class mergesort{
static int A[] = {23,45,10,2,78,32,89,90,1,64};
static int B[] = new int[A.length];
public static void main(String args[]) throws IOException{
// Set up output to a file
PrintStream ps = new PrintStream(new FileOutputStream("out.txt"));
PrintStream pserr = new PrintStream(new FileOutputStream("err.txt"));
System.setOut(ps);
System.setErr(pserr);
MERGE_SORT(A,0,9);
// print sorted array
for(int i=0;i<=9;i++){
System.out.print(Integer.toString(B[i])+" ");
}
}
/**
* Function to merge two sorted arrays
*/
private static void MERGE(int A[],int p,int q,int r){
// variables
int lLimit,rLimit,lp,rp,k;
// initialize variables
lp=0;rp=0;k=0;
// find number of elements in left and right arrays
lLimit = q-p+1;
rLimit = r-q;
// create lists
int L[] = new int[lLimit];
int R[] = new int[rLimit];
for(int i=0;i<lLimit;i++){
L[i] = A[i];
}
for(int i=0;i<rLimit;i++){
R[i] = A[i+lLimit];
}
// sort individual lists
for(int i=0;i<=r;i++){ // runs r times
if(lp>lLimit-1 || rp>rLimit-1) return; // to handle ArrayIndexOutOfBounds
if(L[lp] < R[rp]){
// copy L[lp] to A[k];
A[k] = L[lp];
lp++; // this step could lead to ArrayIndexOutOfBounds error on next check for lp
}else{
A[k] = R[rp];
rp++; // this step could lead to ArrayIndexOutOfBounds error on next check for rp
}
// increment array A's pointer k
k++;
}
}
/**
* Following procedure will result in the creation of individual sorted items
*/
private static void MERGE_SORT(int A[],int p,int r){
if(p<r){
int q = (r-p)/2; // remember, r > p
MERGE_SORT(A,p,q);
MERGE_SORT(A,q+1,r);
MERGE(A,p,q,r);
}
}
}
输出:
Exception in thread "main" java.lang.StackOverflowError
at mergesort.MERGE_SORT(mergesort.java:77)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
at mergesort.MERGE_SORT(mergesort.java:78)
......
答案 0 :(得分:4)
您并未在MERGE_SORT
方法中正确计算范围的中间位置。
int q = (r-p)/2;
应该是
int q = (r+p)/2;
除此问题外,您的MERGE
方法也存在问题。您错误地初始化了L
和R
数组。应为L
数组指定输入数组的p
到q
索引的值(不是从0到q-p
)。应为R
数组分配输入数组的q+1
到r
索引的值。