/*
* p,q,r是下标,满足p<=q<r,假设子糨能a[p..q]与a[q+1..r]已经排好序
* 将两个合并排好序代替当前子数组A[p..r]
* Running time: O(n) n = r-q+1 ÊÇÁœŽýºÏ²¢×ÓÊý×éÔªËصĞöÊýºÍ
*/
void merge(int a[], int p, int q, int r)
{
int *left, *right;
int n1, n2, i, j, k;
n1 = q - p + 1;
n2 = r - q;
left = (int *)malloc(sizeof(int) * (n1+1));
if (left == NULL)
return ;
right = (int *)malloc(sizeof(int) * (n2+1));
if (right == NULL) {
free(left);
return ;
}
for (i = p, n1 = 0; i <= q; ++i, ++n1)
left[n1] = a[i];
for (i = q+1, n2 = 0; i <= r; ++i, ++n2)
right[n2] = a[i];
left[n1] = MAXVAL;
right[n2] = MAXVAL;
i = j = 0;
for (k = p; k <= r; ++k) {
if (left[i] < right[j])
a[k] = left[i++];
else
a[k] = right[j++];
}
free(left);
free(right);
}
/* 递归调用
* O(nlgn)
*/
void merge_sort(int a[], int p, int r)
{
int q;
if (p < r) {
q = (p + r) / 2;
merge_sort(a, p, q);
merge_sort(a, q+1, r);
merge(a, p, q, r);
}
}
* p,q,r是下标,满足p<=q<r,假设子糨能a[p..q]与a[q+1..r]已经排好序
* 将两个合并排好序代替当前子数组A[p..r]
* Running time: O(n) n = r-q+1 ÊÇÁœŽýºÏ²¢×ÓÊý×éÔªËصĞöÊýºÍ
*/
void merge(int a[], int p, int q, int r)
{
int *left, *right;
int n1, n2, i, j, k;
n1 = q - p + 1;
n2 = r - q;
left = (int *)malloc(sizeof(int) * (n1+1));
if (left == NULL)
return ;
right = (int *)malloc(sizeof(int) * (n2+1));
if (right == NULL) {
free(left);
return ;
}
for (i = p, n1 = 0; i <= q; ++i, ++n1)
left[n1] = a[i];
for (i = q+1, n2 = 0; i <= r; ++i, ++n2)
right[n2] = a[i];
left[n1] = MAXVAL;
right[n2] = MAXVAL;
i = j = 0;
for (k = p; k <= r; ++k) {
if (left[i] < right[j])
a[k] = left[i++];
else
a[k] = right[j++];
}
free(left);
free(right);
}
/* 递归调用
* O(nlgn)
*/
void merge_sort(int a[], int p, int r)
{
int q;
if (p < r) {
q = (p + r) / 2;
merge_sort(a, p, q);
merge_sort(a, q+1, r);
merge(a, p, q, r);
}
}