package com.org.example;
import java.util.Arrays;
/**
* @description 归并排序(递归方式) 核心思想:分而治之,先拆分后排序合并归一
*/
public class MergeSort {
public static void main(String[] args) {
int[] arr = { 24, 3, 6, 8, 85, 6, 7 };
sort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
// 拆分
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int mid = (low + high) / 2; // 每次拆分的中点
sort(arr, low, mid); // 中点左边部分,递归拆分
sort(arr, mid + 1, high); // 中点右边部分,递归拆分
mergeSort(arr, low, mid, high); // 开始排序合并
}
}
// 排序合并归一
public static void mergeSort(int[] arr, int left, int mid, int right) {
int[] temp = new int[right - left + 1]; // 定义一个数组,临时存放本轮排序的结果
int t = 0; // 临时数组的指针
int i = left; // 左边部分的指针
int j = mid + 1; // 右边部分的指针
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temp[t++] = arr[i++];
} else {
temp[t++] = arr[j++];
}
}
// 如果第一个while循环结束,左边部分没有完全放进临时数组中,则将剩余部分放入临时数组中
while (i <= mid) {
temp[t++] = arr[i++];
}
// 如果第一个while循环结束,右边部分没有完全放进临时数组中,则将剩余部分放入临时数组中
while (j <= right) {
temp[t++] = arr[j++];
}
// 将排好序的临时数组temp中的元素,逐个放入原来的数组arr中
for (int x = 0; x < temp.length; x++) {
arr[left + x] = temp[x];
}
}
}
排序结果:
[3, 6, 6, 7, 8, 24, 85]