JAVA归并排序学习
视频https://www.bilibili.com/video/BV1E8411e718
package com.horse;
import java.util.Arrays;
public class Sort {
public static void main(String[] args) {
int arr[] = {4, 1, 8, 2, 3, 11, 12, 8, 10, 6};
System.out.println(Arrays.toString(arr));//打印排序前数组
arr = mergeSort(arr, 0, arr.length-1);
System.out.println(Arrays.toString(arr));//打印排序后数组
}
//归并排序
public static int[] mergeSort(int[] nums, int l, int h) {
if (l == h)
return new int[] { nums[l] };
int mid = l + (h - l) / 2;
int[] leftArr = mergeSort(nums, l, mid); //左有序数组
int[] rightArr = mergeSort(nums, mid + 1, h); //右有序数组
int[] newNum = new int[leftArr.length + rightArr.length]; //新有序数组
int m = 0, i = 0, j = 0;
while (i < leftArr.length && j < rightArr.length) {
newNum[m++] = leftArr[i] > rightArr[j] ? leftArr[i++] : rightArr[j++];
}
while (i < leftArr.length)
newNum[m++] = leftArr[i++];
while (j < rightArr.length)
newNum[m++] = rightArr[j++];
return newNum;
}
}