//合并排序的C实现
#include <stdio.h>
#include <malloc.h>
#define INT_MAX 0x7fffffff
void merge(int *a,int p,int q,int r)
{
int n1 = q-p+1;
int n2 = r-q;
int *L = malloc(sizeof(int)*(n1+1));
int *R = malloc(sizeof(int)*(n2+1));
int i,j,k;
for (i=0;i<n1;i++)
{
L[i] = a[p+i];
}
L[i] = INT_MAX;
for (j=0;j<n2;j++)
{
R[j] = a[q+1+j];
}
R[j] = INT_MAX;
i=j=0;
for (k=p;k<=r;k++)
{
if (L[i] <= R[j])
{
a[k] = L[i];i++;
}
else
{
a[k] = R[j];j++;
}
}
}
void merge_sort(int *a,int p,int r)
{
if (p<r)
{
int q = (p+r)/2;
merge_sort(a,p,q);
merge_sort(a,q+1,r);
merge(a,p,q,r);
}
}
int main()
{
int a[100];
int t;
int num;
int i=0;
printf("您有多少个数据?(0~100)");
scanf("%d",&t);
if (t>=0 && t<=100)
{
printf("请输入数据:");
}
else
{
printf("ERROR!\n");
exit(0);
}
num = t;
while(t--)
{
scanf("%d",&a[i++]);
}
merge_sort(a,0,num-1);
for (i=0;i<num;i++)
{
printf("%d ",a[i]);
}
}
合并排序
最新推荐文章于 2023-08-08 16:38:48 发布