public void mergeSort(int[] nums){
if (nums == null || nums.length == 0) return;
int[] temp = new int[nums.length]; //用一个temp数组来保存sort过后的数组
sort(nums, 0, nums.length - 1, temp);
}
private void sort(int[] nums, int start, int end, int[] temp){
if (start >= end) return;
int mid = start + (end - start) / 2;
sort(nums, start, mid, temp); //递归sort左半边
sort(nums, mid+1, end, temp); //di'guisort右半边
merge(nums, start, mid, end, temp); //合并两边
}
private void merge(int[] nums, int start, int mid, int end, int[] temp){
int left = start,
right = mid+1,
i = start;
//如果左边和右边都没到达尾部,则继续,有一个到达尾部了,就停止
while (left <= mid && right <= end){
if (nums[left] < nums[right])
temp[i++] = nums[left++];
else
temp[i++] = nums[right++];
}
//把剩下的全部放到数组里即可
while (left <= mid)
temp[i++] = nums[left++];
while (right <= end)
temp[i++] = nums[right++];
for (int j = start; j <= end; j++)
nums[j] = temp[j];
}