I've written this Java code to implement merge sort:
import java.util.*;
public class MergeSort {
int[] a;
MergeSort() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of items: ");
a = new int[scan.nextInt()];
for (int i = 0; i < a.length; ++i) {
a[i] = scan.nextInt();
}
}
int[] mergeSort2(int beg, int end) {
if (beg == end) {
int []result = new int[]{a[beg]}; /****new array allocation****/
return result;
}
int[] left = mergeSort2(beg, (beg + end) / 2);
int[] right = mergeSort2((beg + end) / 2 + 1, end);
int[] result = new int[end - beg + 1]; /****new array allocation****/
System.out.println("left.length = "+left.length+", right.length = "+right.length+", result.length = "+result.length);
int i, l, r;
for (i = 0, l = 0, r = 0; l < left.length && r < right.length; ++i) {
if (left[l] >= right[r]) {
result[i] = right[r];
r++;
} else if (left[l] < right[r]) {
result[i] = left[l];
l++;
}
}
if (l == left.length) {
for (; r < right.length; ++r, ++i) {
result[i] = right[r];
}
} else if (r == right.length) {
for (; l < left.length; ++l, ++i) {
result[i] = left[l];
}
}
return result;
}
public static void main(String[] args) {
MergeSort ms = new MergeSort();
int[] result = ms.mergeSort2(0, ms.a.length - 1);
System.out.println();
for (int i = 0; i < result.length; ++i) {
System.out.print(result[i] + " ");
}
}
}
Every time I want to return left and right to merge into result, I've to allocate result
again (same for cases where length == 1). How can I avoid this allocation during recursion?