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
| void merge(int a[], int begin, int mid, int end) { int count = end - begin + 1; int* p = new int[count](); int i = begin, j = mid + 1, index = 0; while (i <= mid && j <= end) { p[index++] = a[i] <= a[j] ? a[i++] : a[j++]; } while (j <= end) { p[index++] = a[j++]; } while (i <= mid) { p[index++] = a[i++]; } for (int i = 0; i < count; ++i) { a[begin++] = p[i]; } delete[]p; }
void mergeSort_Recursion(int a[], int begin, int end) { if (begin >= end) { return; } int mid = (begin + end) / 2; mergeSort_Recursion(a, begin, mid); mergeSort_Recursion(a, mid + 1, end); merge(a, begin, mid, end); }
void mergeSort_Iteration(int a[], int begin, int end) { int count = end - begin + 1; int left; for (int step = 1; step < count; step *= 2) { left = begin; while (left + step < end) { int mid = left + step - 1; int right = (mid + step) < end ? (mid + step) : end; merge(a, left, mid, right); left = right + 1; } } }
|