java中的合并排序。有时排序有时进入无限循环

java中的合并排序。有时排序有时进入无限循环,java,sorting,loops,merge,infinite,Java,Sorting,Loops,Merge,Infinite,我正在用java编写一个合并排序。 它有时对数组进行排序,有时进入不定式循环。我不知道为什么。 谢谢你的帮助 // M - Main Array int Aindex = 0; int Bindex = 0; int A[] = new int[(int) (M.length + 1) / 2]; int B[] = new int[(int) M.length / 2

我正在用java编写一个合并排序。 它有时对数组进行排序,有时进入不定式循环。我不知道为什么。 谢谢你的帮助

// M - Main Array
                int Aindex = 0;
                int Bindex = 0;
                int A[] = new int[(int) (M.length + 1) / 2];
                int B[] = new int[(int) M.length / 2];
                while (!sakartotsAugosi(M)) { // While not sorted Look below for this function.
                    Aindex = 0;
                    Bindex = 0;
                    for (int Mindex = 0; Mindex < M.length; Mindex++) {
                        if ((Mindex + 1) % 2 != 0) {
                            A[Aindex] = M[Mindex];
                            Aindex++;
                        } else {
                            B[Bindex] = M[Mindex];
                            Bindex++;
                        }
                    }


                    Aindex = 0;
                    Bindex = 0;
                    for (int Mindex = 0; Mindex < M.length; Mindex++) {
                        if (Aindex == A.length) {
                            M[Mindex] = B[Bindex];
                            Bindex++;
                        } else if (Bindex == B.length) {
                            M[Mindex] = A[Aindex];
                            Aindex++;
                        } else if (A[Aindex] <= B[Bindex]) {
                            M[Mindex] = A[Aindex];
                            Aindex++;
                        } else if (B[Bindex] <= A[Aindex]) {
                            M[Mindex] = B[Bindex];
                            Bindex++;
                        }
                    }
//M-主数组
intaindex=0;
int-Bindex=0;
int A[]=新int[(int)(M.length+1)/2];
int B[]=新int[(int)M.length/2];
while(!sakartotsAugosi(M)){//如果未排序,请在下面查找此函数。
Aindex=0;
Bindex=0;
对于(int-Mindex=0;Mindex}else if(A[Aindex]这不是合并排序的工作方式。我建议您先阅读wiki文章或其他内容,然后重做您的实现。嗯,也许我不知道它的正确名称?它是不同的排序算法吗?不,看起来您试图在这里进行合并排序,但您的方法不正确。您应该将数组分成两部分s、 合并对每个部分进行排序,然后合并它们。您正在执行第一步和最后一步,但不是中间的一步。有关更多信息,请参阅wiki页面。但问题是,这就是我的老师向我展示的方式。问题是,它有时确实排序,有时不排序。但我会查看wiki。:)如果你幸运的话,它只会排序。考虑这个列表:<代码> 0 1,4,2,7,9,3,8,< /代码>。在你的while循环的一次迭代之后,它看起来像什么?
public boolean sakartotsAugosi(int M[]) {
    for (int i = 1; i < M.length; i++) {
        if (M[i - 1] > M[i]) {
            return false;
        }
    }
    return true;
}