Search code examples
javaarraysooprecursionmergesort

mergeSort - destructive vs non destructive in Java


Could anyone explain to me the difference between this non-destructive function implementing the mergeSort algorithm, and a destructive impementation of this function/mergeSort algorithm?

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

}

As mentioned above I know this function returns a "copy" of the input array (non deconstrucitve). How can this be changed to become a destructive function, in other words, the input array itself gets mutated and not a copy produced.


Solution

  • You can overwrite the values in the original array pretty easily, something like this works fine, assuming your mergeSort() method does what it's supposed to.

    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));
    

    This prints:

    [2,5,1,4,3]
    [1,2,3,4,5]