归并排序:即将一个无序序列分为长度大致相同的2部分,然后对这两部分逐个元素比较,将较小的元素放入相应位置
#include "stdio.h"
void merge(int a[], int first, int mid, int end, int temp[])
{
int i,j,k,m,n;
i = first;
j = mid + 1;
m = mid;
n = end;
k = 0;
while(i <= m && j <= n)
{
if(a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while(i <= m)
temp[k++] = a[i++];
while(j <= n)
temp[k++] = a[j++];
for(i = 0; i < k; i++)
a[first + i] = temp[i];
}
void mergesort(int a[], int first, int end)
{
int mid;
int temp[13]={0};
if(first < end)
{
mid = (first + end)/2;
mergesort(a, first, mid);//先将左半部分排好序
mergesort(a, mid + 1, end);//再将右半部分排好序
merge(a, first, mid, end, temp);//将两个排好序的序列重组
}
}
void main()
{
int i;
int a[13] = {92,41,3,5,10,7,9,11,4,17,34,32,130};
mergesort(a, 0, 12);
for(i = 0; i < 13;i++)
printf("%d ",a[i]);
}