mergeSort - Java中的破坏性与非破坏性

时间:2013-03-25 16:08:31

标签: java arrays oop recursion mergesort

有人可以向我解释实现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

}

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

1 个答案:

答案 0 :(得分: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]