0

谁能向我解释这个实现mergeSort算法的非破坏性函数和这个函数/mergeSort算法的破坏性实现之间的区别?

public class MergeSort{

    public static int[] merge(int[] A, int[] B){
        System.out.println("merge: |A|="+A.length+", |B|="+B.length);
        for(int i=0; i<A.length; i+=1) System.out.print(A[i] + ",");
        System.out.println();
        for(int i=0; i<B.length; i+=1) System.out.print(B[i] + ",");
        System.out.println();

        int [] C = new int[ A.length + B.length ];
        int a = 0, b = 0;
        for( int c = 0; c < C.length; c+=1 ){
            if (a == A.length ){
                C[c] = B[b];
                b+=1;
            }else if (b == B.length ){
                C[c] = A[a];
                a+=1;
            }else{
                if (A[a] < B[b]){
                    C[c] = A[a];
                    a+=1;
                }else{
                    C[c] = B[b];
                    b+=1;
                }
            }
        }
        for(int i=0;i<C.length;i+=1) System.out.print(C[i] + ",");
        System.out.println();
        return C;
    }

    public static int[] mergeSort(int[] M){
        System.out.println("mergesort : |M|="+M.length);
        for(int i=0; i<M.length; i+=1) System.out.print(M[i] + ",");
        System.out.println();

        if (M.length ==1){
            int [] C = new int[1]; 
            C[0] = M[0];
            return C;
        }

        int[] A = new int[ M.length/2 ];
        System.arraycopy(M,0,A,0,M.length/2);
        int[] AA = mergeSort(A);
        int[] B = new int[ M.length - M.length/2 ];
        System.arraycopy(M,M.length/2,B, 0, M.length - M.length/2);
        int[] BB = mergeSort(B);

        return merge(AA,BB); 

    }// mergeSort

}

如上所述,我知道此函数返回输入数组的“副本”(非解构)。如何将其更改为破坏性功能,换句话说,输入数组本身会发生突变而不是生成副本。

4

1 回答 1

1

您可以很容易地覆盖原始数组中的值,假设您的 mergeSort() 方法完成了它应该做的事情,这样的事情可以正常工作。

public void overwritingMergeSort(int[] M) {
    int[] sorted = mergeSort(M);
    for(int i = 0; i < sorted.length; i++) {
        M[i] = sorted[i];
    }
}

int[] arr = new int[]{2,5,1,4,3};
System.out.println(Arrays.toString(arr));
overwritingMergeSort(arr);
System.out.println(Arrays.toString(arr));

这打印:

[2,5,1,4,3]
[1,2,3,4,5]
于 2013-03-25T23:52:38.177 回答