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
| void merge(int *nums, int *tmp, int left_start, int right_start, int right_end) { int left_pos, right_pos, pos;
left_pos = left_start; right_pos = right_start; pos = left_start; while (left_pos < right_start && right_pos <= right_end) { if (nums[left_pos] <= nums[right_pos]) tmp[pos++] = nums[left_pos++]; else tmp[pos++] = nums[right_pos++]; }
while (left_pos < right_start) { tmp[pos++] = nums[left_pos++]; } while (right_pos <= right_end) { tmp[pos++] = nums[right_pos++]; }
// copy array tmp back to array nums for (int i=left_start; i<=right_end; i++) nums[i] = tmp[i]; }
void msort(int *nums, int *tmp, int left, int right) { if (left < right) { int center = (left + right) / 2; msort(nums, tmp, left, center); msort(nums, tmp, center+1, right); merge(nums, tmp, left, center+1, right); } }
void merge_sort(int *nums, int n) { int *tmp = new int[n]; msort(nums, tmp, 0, n-1); delete[] tmp; }
|