HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Merge Sort implementation in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortimplementationjavamerge

Problem

Can you check my merge sort implementation? From all of my testing it seems like it works, but I just wanted to make sure I am doing it as good as possible, and it couldn't be optimized any further.

private static void merge(int[] c,int[] a, int[] b){
    int i = 0;//index for a
    int j = 0;//index for b
    for(int k = 0; k = a.length){
            c[k] = b[j];
            j++;
        }else if(j >= b.length){
            c[k] = a[i];
            i++;
        }else if(a[i]  1){
        int pivot = A.length / 2;
        int[] left = Arrays.copyOfRange(A, 0, pivot);
        int[] right = Arrays.copyOfRange(A, pivot,A.length);
        mergeSort(left);
        mergeSort(right);
        merge(A,left,right);
    }
}

Solution

Mostly LGTM, with the following objections.

-
Names. Avoid which require a comment to be understood. I'd have no problem with int ax; because it clearly conveys the goal of being an index of a.

-
Conditionals.

-
You can statically prove that i > a.length is not possible. If by any chance it happens, it means that something really weird is going on. A good cause to raise an exception. Bottomline is, separate a == test from > one.

-
Once one of the ranges is exhausted, there's no need to test it again and again. Normally one would break a main loop and copy the remaining data separately

along the lines of:

while (A has data) and (B has data)
    calculate what to copy
    copy it to C

while (A has data)
    copy A to C

while (B has data)
    copy B to C


  • Types. The methods cry to be generic. If you didn't cover generics yet, disregard the objection.

Code Snippets

while (A has data) and (B has data)
    calculate what to copy
    copy it to C

while (A has data)
    copy A to C

while (B has data)
    copy B to C

Context

StackExchange Code Review Q#59459, answer score: 3

Revisions (0)

No revisions yet.