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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public int[] sortArray(int[] nums) { mergeSort(nums, 0, nums.length - 1); return nums; }
private void mergeSort(int[] nums, int left, int right) { if (left < right) { int mid = left + (right - left) / 2;
mergeSort(nums, left, mid); mergeSort(nums, mid + 1, right); merge(nums, left, mid, right); } }
private void merge(int[] nums, int left, int mid, int right) { int[] temp = new int[right - left + 1]; int i = left, j = mid + 1, k = 0; while (i <= mid && j <= right) { temp[k++] = (nums[i] < nums[j]) ? nums[i++] : nums[j++]; } while (i <= mid) { temp[k++] = nums[i++]; } while (j <= right) { temp[k++] = nums[j++]; } for (i = 0; i < temp.length; i++) { nums[i + left] = temp[i]; } }
|