Version 1
/**
* 归并排序
*/
private static int[] mergeSort(int[] src, int start, int end) {
if (start == end) {
return new int[]{src[start]};
}
int mid = (start + end) / 2;
int[] leftArray = mergeSort(src, start, mid);
int[] rightArray = mergeSort(src, mid + 1, end);
return merge(leftArray, rightArray);
}
/**
* 归并
*/
private static int[] merge(int[] leftArray, int[] rightArray) {
int[] rst = new int[leftArray.length + rightArray.length];
int leftIndex = 0;
int rightIndex = 0;
int rstIndex = 0;
while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
int left = leftArray[leftIndex];
int right = rightArray[rightIndex];
if (left < right) {
rst[rstIndex] = left;
leftIndex++;
} else {
rst[rstIndex] = right;
rightIndex++;
}
rstIndex++;
}
while (leftIndex < leftArray.length) {
rst[rstIndex] = leftArray[leftIndex];
rstIndex++;
leftIndex++;
}
while (rightIndex < rightArray.length) {
rst[rstIndex] = rightArray[rightIndex];
rstIndex++;
rightIndex++;
}
return rst;
}
Version 2 更优
private static void mergeSortRecursive(int[] arr, int[] result, int start, int end) {
if (start >= end)
return;
int len = end - start;
int mid = (len >> 1) + start;
int start1 = start;
int end1 = mid;
int start2 = mid + 1;
int end2 = end;
mergeSortRecursive(arr, result, start1, end1);
mergeSortRecursive(arr, result, start2, end2);
int k = start;
while (start1 <= end1 && start2 <= end2)
result[k++] = arr[start1] <= arr[start2] ? arr[start1++] : arr[start2++];
while (start1 <= end1)
result[k++] = arr[start1++];
while (start2 <= end2)
result[k++] = arr[start2++];
for (k = start; k <= end; k++)
arr[k] = result[k];
}
private static void mergeSort(int[] arr) {
int len = arr.length;
int[] result = new int[len];
mergeSortRecursive(arr, result, 0, len - 1);
}