Java 我的眼睛看不到右边
我的MergeSort代码没有读取右侧。 我认为问题一定出在MergeSort的递归上。如果我把正确的部分放在后面:MergeSortS,q+1,last;在另一个递归之前,它不读取左侧。这是我的密码:Java 我的眼睛看不到右边,java,sorting,recursion,mergesort,Java,Sorting,Recursion,Mergesort,我的MergeSort代码没有读取右侧。 我认为问题一定出在MergeSort的递归上。如果我把正确的部分放在后面:MergeSortS,q+1,last;在另一个递归之前,它不读取左侧。这是我的密码: first = 0; last = S.length; // START - MergeSort public static int[] MergeSort(int[] S,int first,int last){ if(first<last){ int q =
first = 0;
last = S.length;
// START - MergeSort
public static int[] MergeSort(int[] S,int first,int last){
if(first<last){
int q = (first+last)/2;
MergeSort(S,first,q);
MergeSort(S,(q+1),last);
Merge(S,first,q,(q+1),last);
}
return S;
}
public static void Merge(int[] S,int first1,int last1,int first2,int last2){
int N = last1 - first1 + 1;
int M = last2 - first2 + 1;
int Total = N+M-1;
int[] A = new int[N];
int[] B = new int[M];
int[] C = new int[Total];
int posA=0;
int posB=0;
int posC=0;
for(int i=first1; i<N; i++){
A[i] = S[i];
}
for(int i=first2; i<M; i++){
B[i] = S[i];
}
while(posA<N && posB<M){
if(A[posA]<B[posB]){
C[posC]=A[posA];
posA++;
posC++;
}
else{
C[posC]=B[posB];
posB++;
posC++;
}
}
// IF ANYTHING LEFT!
if(posA==N && posB<M){
for(int i=posC;i<Total;i++){
C[i]=B[posB];
posB++;
}
}
if(posB==M && posA<N){
for(int i=posC;i<Total;i++){
C[i]=A[posA];
posA++;
}
}
// DONE!
设置q=first+last-first/2
另外,初始化last=S.length应该将其初始化为last=S.length-1
您可以在中找到一个非常好的实现,请用于所有代码。在这种情况下,应采用适当的方法。不遵守这些约定会使我们更难阅读您的代码,也会弄乱语法突出显示。您的预期输出是什么?因为我刚刚用输出运行了这个示例,它肯定在方法中运行第二个MergeSort?我给它一个数组,例如3,2,5,6,1,它将3与0进行比较。然后是3,2和0。对于第二部分5,6,1,一切都是0。它将0与0进行比较,然后将0与0进行比较。。。编辑!最后,它输出0,0,1,5,6,所以其中一部分消失了。也许我对这个问题的回答,可以帮助你调试你的代码,那肯定不行吗?first==0,因此从p中删除它仍然不会对问题进行排序。递归仍然是一个无限循环。没有帮助。问题仍然存在。@RudiKershaw if语句不是循环。只有在“第一个”小于“最后一个”时,才会输入。输入后,它将对函数进行递归调用。最终first将等于last,并且if语句将不能有效地终止该初始调用的递归。@BrianVanover Right。我所看到的一切都是一样的。我的MergeSort有3个变量,Merge有5个。所以它的处理方式有点不同。@STUDENT_LIFE尝试我刚才提供的第二个更正。