package org.example.leecode;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1};
new MergeSort().sort(arr);
System.out.println(Arrays.toString(arr));
}
public void sort(int[] arr) {
int[] temp = new int[arr.length];
//在排序前,先建好一个长度等于原数组长度的临时数
组,避免递归中频繁开辟空间
sort(arr, 0, arr.length - 1, temp);
}
private static void sort(int[] arr, int left, int
right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
sort(arr, left, mid, temp);
//左边归并排序,使得左子序列有序
sort(arr, mid + 1, right, temp);
//右边归并排序,使得右子序列有序