#include <stdlib.h>
#include <stdio.h>
void merge(int *a,int low,int high,int mid)
{
int *b,i=low,j=mid+1,k=0;
b=(int *)malloc(4*(high-low+1));
while(i<=mid && j<=high)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(i<=mid)
b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(i=low,j=0;i<=high;i++,j++)//将有序数组b复制到a[low]-a[high]中。
a[i]=b[j];
free(b);
}
void mergesort(int *a,int low,int high)
{
int mid=(high+low)/2;
if(low<high)
{
//将数组不断划分为两个部分
mergesort(a,low,mid);
mergesort(a,mid+1,high);
//将两个部分组合并为一个有序的数组
merge(a,low,high,mid);
}
}
void main()
{
int a[10]={23,45,13,24,35,67,11,24,35,31};
mergesort(a,0,9);
for(int i=0;i<=9;i++)
printf("%d ",a[i]);
printf("\n");
}
归并排序
最新推荐文章于 2023-12-11 10:45:47 发布