简体   繁体   English

为什么合并排序的这种实现不起作用?

[英]Why is this implementation of merge sort not working?

I took help from Here but I particularly don't want to declare my methods as void. 我从这里获得了帮助,但我尤其不想将我的方法声明为无效。 Any help would be appreciated! 任何帮助,将不胜感激!

class merges{
public static void main (String args[]){
    int[] A = {10,9,8,7,6,5,4,3,2,1};

    for(int i =0; i< A.length; i++){
        System.out.print(A[i]+" ");
    }
    System.out.println();

    A = mergesort(A,0,A.length-1);

    for(int i =0; i< A.length; i++){
        System.out.print(A[i]+" ");
    }
    System.out.println();
}

static int[] mergesort(int[]A,int l, int r){
    if(l >= r){
        return A;
    }
    else{
        int mid = (l+r)/2;
        mergesort(A,l,mid);
        mergesort(A,mid+1,r);
        return merge(A,l,r);
    }
}

static int[] merge( int[]A, int l, int r){
    int m = (l+r)/2;
    int[]L = new int[m-l+1];
    int[]R = new int[r-m];

    for(int i=0; i<m-l+1; i++ ){
        L[i] = A[l+i];
    }
    for(int i=0; i<r-m; i++ ){
        R[i] = A[m+i+1];
    }

    int i =0;
    int j =0;
    int []B = new int[A.length];
    int k=0;

    while (i<L.length && j<R.length){
        if(L[i]<R[j]){
            B[k] = L[i];
            i++;
        }
        else{
            B[k] = R[j];
            j++;
        }
        k++;
    }

    while(i<L.length){
        B[k] = L[i];
        k++;
        i++;
    }
    while(j<R.length){
        B[k] = R[j];
        k++;
        j++;
    }
    return B;
}
}

This is my implementation of merge sort, The output I get is 5 4 3 2 1 10 9 8 7 6. 这是我实现的归类排序,我得到的输出是5 4 3 2 1 10 9 8 7 6。

Can anyone help me in figuring out how can I make this work? 谁能帮助我弄清楚如何进行这项工作?

I don't want to declare the mergesort and merge methods as void, I want them to return the sorted array instead. 我不想将mergesort和merge方法声明为void,而是希望它们返回排序后的数组。 Thanks in advance. 提前致谢。

The problem is that your merge function returns a new array, but you are calling it as if you intend it to modify A in place. 问题是您的merge函数返回了一个新数组,但是您正在调用它,就好像您打算让它就地修改A

You could fix this by copying B into A at the end of the merge function: 您可以通过在merge功能末尾将B复制到A中来解决此问题:

k = 0;
for(int i=l; i<r; i++ ){
    A[i] = B[k++];
}
int k=l;

while (i<L.length && j<R.length){
    if(L[i]<R[j]){
        A[k] = L[i];
        i++;
    }
    else{
        A[k] = R[j];
        j++;
    }
    k++;
}

while(i<L.length){
    A[k] = L[i];
    k++;
    i++;
}
while(j<R.length){
    A[k] = R[j];
    k++;
    j++;
}
return A;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM