源代码地址:图解排序算法(四)之归并排序 - dreamcatcher-cx - 博客园
我对其代码加入了更详细的注释
import java.util.Arrays;
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 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++];
}
}
}



