归并排序精简版
作者:互联网
class Solution {
int[] tmp; //临时数组复制使用
public int[] sortArray(int[] nums) {
tmp = new int[nums.length];
mergeSort(nums, 0, nums.length - 1);
return nums;
}
public void mergeSort(int[] nums, int l, int r) {
if (l >= r) return;
int mid = (l + r) >> 1; mergeSort(nums, l, mid); mergeSort(nums, mid + 1, r); int i = l, j = mid + 1; //两个数组的起始坐标 int cnt = 0; //合并数组的下标 while (i <= mid && j <= r) { //合并两个有序数组 if (nums[i] <= nums[j]) { tmp[cnt++] = nums[i++]; } else { tmp[cnt++] = nums[j++]; } } while (i <= mid) { //处理没复制完的 tmp[cnt++] = nums[i++]; } while (j <= r) { tmp[cnt++] = nums[j++]; } for (int k = 0; k < r - l + 1; ++k) { //转回原数组 nums[k + l] = tmp[k]; } } }
int mid = (l + r) >> 1; mergeSort(nums, l, mid); mergeSort(nums, mid + 1, r); int i = l, j = mid + 1; //两个数组的起始坐标 int cnt = 0; //合并数组的下标 while (i <= mid && j <= r) { //合并两个有序数组 if (nums[i] <= nums[j]) { tmp[cnt++] = nums[i++]; } else { tmp[cnt++] = nums[j++]; } } while (i <= mid) { //处理没复制完的 tmp[cnt++] = nums[i++]; } while (j <= r) { tmp[cnt++] = nums[j++]; } for (int k = 0; k < r - l + 1; ++k) { //转回原数组 nums[k + l] = tmp[k]; } } }
标签:tmp,归并,精简版,nums,int,mid,++,cnt,排序 来源: https://www.cnblogs.com/zwcmt/p/15018373.html