In-Place Merge and the Common Merge
One int array holds two sorted halves: arr[0] through arr[mid - 1] is sorted, and arr[mid] through arr[arr.length - 1] is sorted.
Solution
Start k at 0 and move it through the first half. If arr[k] is greater than arr[mid], then arr[mid] belongs at position k: shift arr[k] through arr[mid - 1] one position to the right, put the old arr[mid] at position k, and move both k and mid right by one. Otherwise arr[k] is already in its final position; move k right by one. Stop when k reaches mid or mid reaches arr.length.
Solution
Auxiliary space . Worst-case time : when every element of the second half is smaller than every element of the first half, each of the insertions shifts elements.
Solution
private static void merge(int[] arr, int start, int mid, int end) {
int[] merged = new int[end - start];
int i = start, j = mid;
for (int k = 0; k < merged.length; k++) {
if (i >= mid) {
merged[k] = arr[j++];
} else if (j >= end) {
merged[k] = arr[i++];
} else if (arr[i] <= arr[j]) {
merged[k] = arr[i++];
} else {
merged[k] = arr[j++];
}
}
for (int k = 0; k < merged.length; k++) {
arr[start + k] = merged[k];
}
}
Solution
Time : each of the two loops runs times, one to fill merged and one to copy it back into arr. Auxiliary space , the merged array.