简体   繁体   中英

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.

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. 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.

You could fix this by copying B into A at the end of the merge function:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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