public class MergeSort {
public static void mergeSort(int[] array) {
if (array.length <= 1) {
return;
}
int mid = array.length / 2;
// 分割原始数组为两个子数组
int[] leftArray = new int[mid];
int[] rightArray = new int[array.length - mid];
System.arraycopy(array, 0, leftArray, 0, mid);
System.arraycopy(array, mid, rightArray, 0, array.length - mid);
// 递归对子数组进行归并排序
mergeSort(leftArray);
mergeSort(rightArray);
// 合并两个有序子数组
merge(leftArray, rightArray, array);
}
private static void merge(int[] leftArray, int[] rightArray, int[] mergedArray) {
int leftLength = leftArray.length;
int rightLength = rightArray.length;
int i = 0, j = 0, k = 0;
while (i < leftLength && j < rightLength) {
if (leftArray[i] <= rightArray[j]) {
mergedArray[k++] = leftArray[i++];
} else {
mergedArray[k++] = rightArray[j++];
}
}
while (i < leftLength) {
mergedArray[k++] = leftArray[i++];
}
while (j < rightLength) {
mergedArray[k++] = rightArray[j++];
}
}
public static void main(String[] args) {
int[] array = {9, 5, 7, 1, 3, 6, 2, 8, 4};
System.out.println("原始数组:");
printArray(array);
mergeSort(array);
System.out.println("排序后数组:");
printArray(array);
}
private static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}