I tried to put MergeSort into code (see below). The problem is: it doesn't sort correctly in any case. 55,6% (of 1000 random Arrays) are sorted correctly, the rest ist not. I cannot figure out whats wrong. Any help/hints would be appreciated:
import java.util.Arrays;
public class MergeSort {
public static void sort(int[] a){
if (a.length > 1){
int[] left = Arrays.copyOfRange(a,0,a.length/2);
int[] right = Arrays.copyOfRange(a,a.length/2,a.length);
sort(left);
sort(right);
a = merge(left,right);
}
}
private static int[] merge (int[] a, int[] b){
int[] c = new int[a.length+b.length];
int i = 0, j=0, k=0;
while ((i < a.length) && (j <b.length)){
if (a[i] < b[j]) c[k++] = a[i++];
else c[k++] = b[j++];
}
while (i<a.length) c[k++] = a[i++];
while (j<b.length) c[k++] = b[j++];
return c;
}
}