首页 > 代码库 > 归并排序

归并排序

#include<stdio.h>#define MAXSIZE 20typedef int KeyType;typedef struct{    KeyType  key;}RcdType;typedef struct {    RcdType r[MAXSIZE+1];    int length;}Sqlist;void Merge(RcdType sr[],RcdType tr[],int s,int m,int t){    int i, k,j;    j=m+1;i=s;k=s;    while(i<=m&&j<=t)    if(sr[i].key<=sr[j].key)        tr[k++]=sr[i++];    else         tr[k++]=sr[j++];    while(i<=m)        tr[k++]=sr[i++];    while(j<=t)        tr[k++]=sr[j++]; }void Msort(RcdType sr[],RcdType tr1[],int s,int t){ int m; RcdType tr2[MAXSIZE+1];    if(s==t)        tr1[s]=sr[s];    else{        m=(s+t)/2;        Msort(sr,tr2,s,m);        Msort(sr,tr2,m+1,t);        Merge(tr2,tr1,s,m,t);    }}void  MergeSort(Sqlist &L){Msort(L.r,L.r,1,L.length);}void main(){Sqlist A; int i; printf("\n请输入待排序的个数"); scanf("%d",&A.length); printf("\n请输入待排序的数字"); for(i=1;i<=A.length;i++)  scanf("%d",&A.r[i].key); MergeSort(A); printf("\n排好序的数字为"); for(i=1;i<=A.length;i++)  printf("%d ",A.r[i].key);}

 

归并排序