I have made a merge sort algorithm but am unsure of the 'Space Usage' of the algorithm.
public class Sorting {
public static void mergeSort(int[] arr) {
if (arr.length == 1) {
return;
}
int[] newArrLeft = new int[arr.length / 2];
int[] newArrRight = new int[arr.length - (arr.length / 2)];
int currentRight = 0;
for (int i = 0; i < arr.length; i++) {
if (i < arr.length / 2) {
newArrLeft[i] = arr[i];
} else {
newArrRight[currentRight++] = arr[i];
}
}
mergeSort(newArrLeft);
mergeSort(newArrRight);
merge(newArrLeft, newArrRight, arr);
}
private static void merge(int[] arrLeft, int[] arrRight,
int[] sortedValuesArr) {
int currentLeft = 0;
int currentRight = 0;
int currentSorted = 0;
while (currentLeft < arrLeft.length && currentRight < arrRight.length) {
if (arrLeft[currentLeft] < arrRight[currentRight]) {
sortedValuesArr[currentSorted++] = arrLeft[currentLeft++];
} else {
sortedValuesArr[currentSorted++] = arrRight[currentRight++];
}
}
while (currentLeft < arrLeft.length) {
sortedValuesArr[currentSorted++] = arrLeft[currentLeft++];
}
while (currentRight < arrRight.length) {
sortedValuesArr[currentSorted++] = arrRight[currentRight++];
}
}
}
I am specifically inquiring about:
int[] newArrLeft = new int[arr.length / 2];
int[] newArrRight = new int[arr.length - (arr.length / 2)];
int currentRight = 0;
for (int i = 0; i < arr.length; i++) {
if (i < arr.length / 2) {
newArrLeft[i] = arr[i];
} else {
newArrRight[currentRight++] = arr[i];
}
}
Is the above code wasting space? Is there a better implementation?