2020-07-04(C语言)数据结构归并排序

//归并排序

include

include

define MAXSIZE 100

typedef struct SqList
{
int r[MAXSIZE + 1];
int length;
} SqList;
void Merge(int R[], int T[], int low, int mid, int high) //将有序表R[low...mid]和R[mid+1...high]归并为有序表T[low...high]
{
int i, j, k;
i = low;
j = mid + 1;
k = low;
while (i <= mid && j <= high) //将R中记录由小到大地并入T中
{
if (R[i] <= R[j])
{
T[k++] = R[i++];
}
else
{
T[k++] = R[j++];
}
}
while (i <= mid) //将剩余的R[i...mid]复制到T中
{
T[k++] = R[i++];
}
while (j <= high) //将剩余的R[j.high]复制到T中
{
T[k++] = R[j++];
}
}
void MSort(int R[], int T[], int low, int high) //R[low..high]归并排序后放入T[low..high]中
{
int mid;
int S[20];
if (low == high)
{
T[low] = R[low];
}
else
{
mid = (low + high) / 2; //将当前序列一分为二,求出分裂点mid
MSort(R, S, low, mid); //对子序列R[low..mid]递归归并排序,结果放入S[low..mid]
MSort(R, S, mid + 1, high); //对子序列R[mid+1..high]递归归并排序,结果放入S[mid+1..high]
Merge(S, T, low, mid, high); //将S[low..mid]和S[mid+1..high]归并到T[low..high]
}
}
void MergeSort(SqList *L) //对顺序表L做归并排序
{
MSort(L->r, L->r, 1, L->length);
}
int main()
{
SqList *L;
int i;
L = (SqList *)malloc(sizeof(SqList));
printf("请输入长度:");
scanf("%d", &L->length);
printf("请输入元素:");
for (i = 1; i <= L->length; i++)
{
scanf("%d", &L->r[i]);
}
printf("排序前:");
for (i = 1; i <= L->length; i++)
{
printf("%d ", L->r[i]);
}
printf("\n");
MergeSort(L);
printf("排序后:");
for (i = 1; i <= L->length; i++)
{
printf("%d ", L->r[i]);
}
printf("\n");
return 0;
}

你可能感兴趣的:(2020-07-04(C语言)数据结构归并排序)