package sort;
public class MergeSorting {
public static void mergeSort(int[] nums, int start, int end){
if (start == end) //终止条件(细品)
return;
int mid = (start + end)/2; //数组二分
mergeSort(nums, start, mid); //对数组左半边排序
mergeSort(nums, mid + 1, end);//对数组右半边排序
merge(nums, start, mid, end);//合并两个有序数组
}
//合并两个有序数组
private static void merge(int[] nums,int start, int mid, int end){
if (start > end)
return;
int i = start;
int j = mid + 1;
int[] res = new int[nums.length];
int k = start; //新数组的下标
while (i <= mid && j <= end ){
if ( nums[i] <= nums[j])//当左边数组小于右边数组就一直将左边复制到新数组
res[k++] = nums[i++]; //细品,此处的处理尤为高效精简!
else //当右边数组小于左边数组就一直将右边复制到新数组
res[k++] = nums[j++];
}
//当i或j中一个到达右边界上述循环退出
//此时将未复制的数组片段全部复制到新数组
while (i <= mid)
res[k++] = nums[i++];
while (j <= end)
res[k++] = nums[j++];
//将有序数组复制到nums
for (int h = start; h <= end; h++)
nums[h] = res[h];
}
public static void main(String[] args){
int[] nums = {2,0,1,9,1,0,2,8};
mergeSort(nums, 0, nums.length - 1);
for (int num: nums)
System.out.print(num+" ");
}
}