I just learned Merge sort, and I really like this Merge sort implementation since it is very logical and very easy to follow. If I was asked in an interview to implement merge sort, will this implementation suffice?
I know creating those new arrays every time the mergeSort()
method is called is bad practice. I fully understand merge sort, I can explain it in very good detail as I implement it, but will this implementation lose me some "points" because of the the way I am creating all these new arrays?
Are there any other things that may lose me some points?
public static void mergeSort(int[] a) {
if(a.length < 2) return;
int mid = a.length / 2;
int[] left = new int[mid];
int[] right = new int[a.length - mid];
//Filling left and right arrays.
for(int i = 0; i < left.length; i++)
left[i] = a[i];
for(int i = 0; i < right.length; i++)
right[i] = a[i + mid];
mergeSort(left);
mergeSort(right);
merge(left, right, a);
}
public static void merge(int[] left, int[] right, int[] a) {
int i = 0; //For left array
int j = 0; //For right array
int k = 0; //For a array
while(i < left.length && j < right.length) {
if(left[i] <= right[j])
a[k++] = left[i++];
else
a[k++] = right[j++];
}
//Filling remaining integers, for the array that has left over numbers.
while(i < left.length)
a[k++] = left[i++];
while(j < right.length)
a[k++] = right[j++];
}
This is tested and working.