源代码地址:图解排序算法(四)之归并排序 - dreamcatcher-cx - 博客园
我对其代码加入了更详细的注释
import java.util.Arrays;
/**
* @author teen
* @create 2021/11/5 7:23
*/
public class Test01 {
public static void main(String[] args) {
//定义要排序的数组
int[] arr = {2,5,8,9,1,3,14,4,6,7,11,6,2,13};
//定义缓存数组用来存放两个子数组的归并数组
int[] temp = new int[arr.length];
//对arr全体排序
sort(arr,0,arr.length-1,temp);
//打印数组
System.out.println(Arrays.toString(arr));
}
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);
//分完后开始“治” 排序 并合并两个子数组 以中间界为分割的两个子数组
marge(arr,left,mid,right,temp);
}
}
//核心代码
private static void marge(int[] arr, int left, int mid, int right, int[] temp) {
//确定左边数组的第一个元素
int leftIndex = left;
//确定右边数组的第一个元素
int rightIndex = mid+1;
//临时数组的下标
int tempIndex = 0;
//现在开始比大小
//左数组的第一个元素和右数组的第一个元素比较,谁大谁先加入temp 直到其中一个到达边界
while (leftIndex<=mid && rightIndex<=right){
//如果左边数组的第一个数大于右边
if (arr[leftIndex] > arr[rightIndex]){
//将右子数组的第一个数放入临时数组后 指针后移
temp[tempIndex++] = arr[rightIndex++];
}else {
//否则将左子数组的第一个数放入临时数组 指针后移
temp[tempIndex++] = arr[leftIndex++];
}
}
//如果左边数组存在没排进去的,一股脑加进去
while (leftIndex<=mid){
temp[tempIndex++] = arr[leftIndex++];
}
//如果右边数组有剩余的,一股脑加进去
while (rightIndex <=right){
temp[tempIndex++] = arr[rightIndex++];
}
//此时temp中便保留了两个子数组排序完成的归并数组
//先将temp数组指针归位
tempIndex = 0;
//将有序归并数组整理到原数组
while (left<=right){
arr[left++] = temp[tempIndex++];
}
}
}