核心代码:
/*将相邻的有序区间SR[i...m]和SR[m+1,n]归并为有序的TR[i...n]*/
void Merge(RcdType SR[], RcdType TR[], int i, int m, int n)
{
int j, k;
for (j = m + 1, k = i; i <= m && j <= n; k++) {
if (SR[i].key <= SR[j].key) { //'<='改为'<'排序会变不稳定
TR[k].key = SR[i++].key;
}
else TR[k].key = SR[j++].key;
}
while (i <= m) TR[k++].key = SR[i++].key;
while (j <= n) TR[k++].key = SR[j++].key;
}
/*R1,R2交替归并*/
void MergeSort(RcdType R1[], RcdType R2[], int i, int s, int t)
{
/*i%2 == 1 R1归并排序到R2*/
int m;
if (s == t) {
if (i % 2 == 1) R2[s] = R1[s]; //单个元素直接复制过去
}
else {
m = (s + t) / 2;
MergeSort(R1, R2, i + 1, s, m);
MergeSort(R1, R2, i + 1, m + 1, t);
if (i % 2 == 1) Merge(R1, R2, s, m, t);
else Merge(R2, R1, s, m, t);
}
}
#include <stdio.h>
#include <stdlib.h>
#include "data_structure.h"
#include "msort.h"
Status InitRcdList(RcdList &L, KeyType key[], int n)
{
if (n <= 0) return ERROR;
L.rcd = (RcdType*)malloc((n + 1)*sizeof(RcdType));
if (L.rcd == NULL) return ERROR;
L.length = n;
for (int i = 1; i <= n; i++)
L.rcd[i].key = key[i - 1];
return OK;
}
void PrintRcdList(RcdList list)
{
for (int i = 1; i <= list.length; i++)
printf("%d ", list.rcd[i].key);
printf("\n");
}
int main()
{
RcdList list;
KeyType key[7] = { 42, 30, 68, 98, 86, 15, 57 };
InitRcdList(list, key, 7);
PrintRcdList(list);
RcdType *R;
R = (RcdType*)malloc((list.length + 1)*sizeof(RcdType));
MergeSort(list.rcd, R, 0, 1, list.length);
PrintRcdList(list);
system("pause");
return 0;
}