首页 > 代码库 > 归并排序

归并排序

#include<stdio.h>void MergeArray(int first,int mid,int last,int a[]){    int k=0;    int i=first,j=mid+1;    int n=mid,m=last;    int c[100];    while(i<=n && j<=m)    {        if(a[i]<a[j]) c[k++]=a[i++];        else c[k++]=a[j++];    }    while(i<=n) c[k++]=a[i++];    while(j<=m) c[k++]=a[j++];    for(i=0;i<k;i++) a[i+first]=c[i];}void MergeSort(int first,int last,int a[]){    if(first==last) return ;    int mid=(first+last)/2;    MergeSort(first,mid,a);    MergeSort(mid+1,last,a);    MergeArray(first,mid,last,a);}int main(){    int a[100],c[100],n;    while(scanf("%d",&n))    {        for(int i=0;i<n;i++) scanf("%d",&a[i]);        MergeSort(0,n-1,a);        for(int i=0;i<n;i++) printf("%d ",a[i]);        printf("\n");    }}