归并排序是用一种分而治之的方法将一个数组划分为越来越小的半子表,再对半子表的元素进行排序,最后用递归将一个一个有序的半子表合成出一个越来越大的有序数组。
先定义一个mergeArray的方法,该方法是用于将一个从mid分开,两边都有序的数组合并成一个有序数组存入temp中,再送回数组array中:
void mergeArray(int array[],int first,int mid,int last,int temp[]){
int indexA=first;
int indexB=mid+1;
int k=0;
int i;
while(indexA<=mid&&indexB<=last){
if(array[indexA]<array[indexB]){
temp[k]=array[indexA];
k++;
indexA++;
}
else{
temp[k]=array[indexB];
k++;
indexB++;
}
}
while(indexA<=mid){
temp[k]=array[indexA];
k++;
indexA++;
}
while(indexB<=last){
temp[k]=array[indexB];
k++;
indexB++;
}
for(i=0;i<k;i++){
array[first+i]=temp[i];
}
接着定义一个函数mergeSort,它有4个参数,待排序的数组array,数组首下标和数组最后下标,还有中间数组temp,这个函数用递归的方法将一个数组先划分为很多个只有两个数据的小数组,再将这些小数组合并成一个大数组,便完成了归并排序。
void mergeSort(int array[],int first,int last,int temp[]){
if(first<last){
int mid=(first+last)/2;
mergeSort(array,first,mid,temp); //左子表有序
mergeSort(array,mid+1,last,temp); //右子表有序
mergeArray(array,first,mid,last,temp); //将两个有序表整合成一个有序表
}
}
完整的程序如下:
#include
#include
void mergeArray(int array[],int first,int mid,int last,int temp[]){
int indexA=first;
int indexB=mid+1;
int k=0;
int i;
while(indexA<=mid&&indexB<=last){
if(array[indexA]
测试主函数
int main()
{
int a[10];
int i;
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
MergeSort(a,10);
for(i=0;i<10;i++)
{
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
运行结果