1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int[] sortArray(int[] nums) { if (nums.length < 2) { return nums; } process(nums, 0, nums.length - 1); return nums; }
public void process(int[] nums, int left, int right) { if (left == right) { return; } int mid = left + ((right - left) >> 1); process(nums, left, mid); process(nums, mid + 1, right); merge(nums, left, right, mid); }
public void merge(int[] nums, int left, int right, int mid) { int[] help = new int[right - left + 1]; int i = 0; int leftPoint = left; int rightPoint = mid + 1; while (leftPoint <= mid && rightPoint <= right) { help[i++] = nums[leftPoint] < nums[rightPoint] ? nums[leftPoint++] : nums[rightPoint++]; } while (leftPoint <= mid) { help[i++] = nums[leftPoint++]; } while (rightPoint <= right){ help[i++] = nums[rightPoint++]; } for (int j = 0; j < help.length; j++) { nums[left + j] = help[j]; } } }
|