#include <stdio.h>
#include <stdlib.h>
void merge(int a[],int p ,int q,int r)
{
int i,j,k,n1,n2;
int *front,*back;
n1 = q-p+1;
n2 = r-q;
front = (int *)malloc(n1 * sizeof(int));
back = (int *)malloc(n2 * sizeof(int));
/* 将数组转入两个新空间中 */
for(i=0;i<n1;i++)
{
front[i] = a[p+i];
}
for(i=0;i<n2;i++)
{
back[i] = a[q+i+1];
}
/* 将元素合并 */
i = 0;
j = 0;
k = p;
while(i<n1 && j<n2)
{
if(front[i]<= back[j])
{
a[k++] = front[i++];
}
else
{
a[k++] = back[j++];
}
}
/* 将剩余的元素合并 */
while(i<n1)
{
a[k++] = front[i++];
}
while(j<n2)
{
a[k++] = back[j++];
}
}
void merge_sort(int a[],int p,int r)
{
int q;
if(p<r)
{
q = (p+r)/2;
merge_sort(a,p,q);
merge_sort(a,q+1,r);
merge(a,p,q,r);
}
}
int main()
{
int a[8] = {1,9,2,6,3,7,4,8};
int i ;
merge_sort(a,0,7);
for(i=0;i<8;i++)
{
printf("%d ",a[i]);
}
system("pause");
return 0;
}
归并排序的简单实现
最新推荐文章于 2024-09-24 23:16:04 发布