package mytest; import java.util.Arrays; /** * @author :l_coil * @date :2021/12/11 9:29 下午 * 归并排序 */ public class MergeSort { public static void main(String[] args) { int[] ints = {3, 1, 4, 8, 7, 5, 2}; int[] result = sort(ints); System.out.println(Arrays.toString(result)); } public static int[] sort(int[] sourceArray) { int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); //只有一个元素 if (arr.length < 2) { return arr; } // 取出将整体划分为 2 路的中间节点 int middle = (int) Math.floor(arr.length / 2); // 递归划分子集—逐步裂变 int[] left = sort(Arrays.copyOfRange(arr, 0, middle)); int[] right = sort(Arrays.copyOfRange(arr, middle, arr.length)); // 合并,通过改变递归数组的长度,逐步收拢子集 return merge(left, right); } public static int[] merge(int[] left, int[] right) { int[] result = new int[left.length + right.length]; int i = 0; // 归并已排序两个子集 while (left.length > 0 && right.length > 0) { if (left[0] <= right[0]) { result[i++] = left[0]; left = Arrays.copyOfRange(left, 1, left.length); } else { result[i++] = right[0]; right = Arrays.copyOfRange(right, 1, right.length); } } // 假如两个数组大小比对排序合并之后,left数组还存有剩余比之前元素大的,直接将剩余元素添加到合并集 while (left.length > 0) { result[i++] = left[0]; left = Arrays.copyOfRange(left, 1, left.length); } // 假如两个数组大小比对排序合并之后,right数组还存有剩余比之前元素大的,直接将剩余元素添加到合并集 while (right.length > 0) { result[i++] = right[0]; right = Arrays.copyOfRange(right, 1, right.length); } return result; } }