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
| void merge(vector<int>& nums, int low, int mid, int high) { vector<int> numsCpy(high - low + 1); int p1 = low, p2 = mid + 1, p3 = 0; while (p1 <= mid && p2 <= high) { if (nums[p1] <= nums[p2]) { numsCpy[p3++] = nums[p1++]; } else { numsCpy[p3++] = nums[p2++]; } } while (p1 <= mid) numsCpy[p3++] = nums[p1++]; while (p2 <= high) numsCpy[p3++] = nums[p2++]; for (int i = 0; i < numsCpy.size(); ++i) { nums[low++] = numsCpy[i]; } }
void recurSort(vector<int>& nums, int low, int high) { if (low >= high) return; int mid = low + (high - low) / 2; recurSort(nums, low, mid); recurSort(nums, mid + 1, high); merge(nums, low, mid, high); }
void mergeSort(vector<int>& nums) { recurSort(nums, 0, nums.size() - 1); }
|