如果归并排序中待归并的两个相邻序列分别Wi是r[start]~r[mid]和r[mid+1]~r[end],需要将其归并成一个新序列r1[start]~r1[end]:
void merge(int r[], int r1[], int start, int mid, int end)
{
int i = start, j = mid + 1, k = start;
while (i <= mid && j <= end)
r1[k++] = (r[i] < r[j] ? r[i++] : r[j++]);
memcpy(r1 + k, r + i, (mid - i + 1) * sizeof(int)); k += mid - i + 1;
memcpy(r1 + k, r + j, (end - j + 1) * sizeof(int)); k += end - j + 1;
}
一趟归并排序:
void MergePass(int r[], int r1[], int n, int h)
{
int i = 1;
while (i < n - h * 2 + 1)
{
merge(r, r1, i , i + h - 1, i + h * 2 - 1);
i += (h * 2);
}
if (i < n - h + 1) merge(r, r1, i, i + h - 1, n);
else memcpy(r1 + i, r + i, (n - i + 1) * sizeof(int));
}
归并排序主函数:
void MergeSort(int r[], int n)
{
int *r1 = new int [n + 1];
int h = 1;
while (h < n)
{
MergePass(r, r1, n, h);
h <<= 1;
if (h >= n)
{
memcpy(r, r1, (n + 1) * sizeof(int));
break;
}
MergePass(r1, r, n, h);
h <<= 1;
}
delete r1[];
}
原文地址:http://blog.csdn.net/chfe007/article/details/44157563