归并排序原理:
1、将一个数组一分为二
2、递归处理前后段,使前后半有序
3、将前后半段进行归并得到有序数组
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {2, 1, 4, 3, 5, 7, 6, 9, 8, 0};
mergeSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
private static void mergeSort(int[] arr, int l, int r) {
if (l >= r) return;
int mid = (l + r) >>> 1;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
int i = l, j = mid + 1, k = 0;
int[] memo = new int[r - l + 1];
while (i <= mid) {
while (j <= r && arr[i] > arr[j]) memo[k++] = arr[j++];
memo[k++] = arr[i++];
}
while (j <= r) memo[k++] = arr[j++];
System.arraycopy(memo, 0, arr, l, k);
}
}