废话不多说直接上代码
#include <stdio.h>
#include <stdlib.h>
int Length;
int *A;
int *B;
void MergeSort(int *A, int low, int high);
void Merge(int *A, int low, int mid, int high);
void printnums(int *A);
int main()
{
puts("请输入待排序数组的长度:");
scanf("%d", &Length);
A = (int *)malloc(sizeof(int) * Length);
B = (int *)malloc(sizeof(int) * Length);
puts("请输入待排序数组:");
for (int i = 0; i < Length; i++)
{
scanf("%d", &A[i]);
}
MergeSort(A, 0, Length - 1);
printnums(A);
system("pause");
return 0;
}
void Merge(int *A, int low, int mid, int high)
{
for (int i = low; i <= high; i++)
{
B[i] = A[i];
}
int i, j, k;
for (i = low, j = mid + 1, k = i; i <= mid && j <= high; k++)
{
if (B[i] <= B[j])
{
A[k] = B[i++];
}
else
{
A[k] = B[j++];
}
}
while (i <= mid)
{
A[k++] = B[i++];
}
while (j <= high)
{
A[k++] = B[j++];
}
}
void MergeSort(int *A, int low, int high)
{
if (low < high)
{
int mid = (low + high) / 2;
MergeSort(A, low, mid);
MergeSort(A, mid + 1, high);
Merge(A, low, mid, high);
}
}
void printnums(int *A)
{
for (int i = 0; i < Length; i++)
{
printf("%d ", A[i]);
}
puts("");
}
如有错误欢迎指正!