归并排序

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define OK 1
 4 #define FALSE 0
 5 #define MAX_NUM 100
 6 typedef int Status;
 7 typedef int ElemType;
 8 typedef struct SqList
 9 {
10     ElemType r[MAX_NUM];
11     int length;
12 }SqList;
13 void Merge(ElemType SR[],ElemType TR[],int i,int m,int n)
14 {
15     int j,k;
16     for(j=m+1,k=i;i<=m&&j<=n;k++)
17     {
18         if(SR[i]<SR[j]) TR[k]=SR[i++];
19         else TR[k]=SR[j++];
20     }
21     while(i<=m) TR[k++]=SR[i++];
22     while(j<=n) TR[k++]=SR[j++];
23 } 
24 void MSort(ElemType SR[],ElemType TR1[],int s,int t)
25 {
26     int m;
27     ElemType TR2[MAX_NUM];
28     if(s==t) TR1[s]=SR[s];
29     else 
30     {
31         m=(s+t)/2;
32         MSort(SR,TR2,s,m);
33         MSort(SR,TR2,m+1,t);
34         Merge(TR2,TR1,s,m,t);
35     }
36 }
37 void MergeSort(SqList &L)
38 {
39     MSort(L.r,L.r,1,L.length);
40 }
41 
42 Status main()
43 {
44     SqList L;
45     int i,dlta[5]={1};
46     puts("请输入待排序数组的元素个数:");
47     scanf("%d",&L.length);
48     puts("请输入你要排序的数组:");
49     for(i=1;i<=L.length;i++)
50     scanf("%d",&L.r[i]);
51     
52     MergeSort(L);
53     
54     
55     puts("排序后结果为:");
56     for(i=1;i<=L.length;i++)
57     printf("%-3d",L.r[i]);
58     putchar('\n');
59     system("pause");
60     return OK; 
61 } 

posted on 2012-08-03 09:22  mycapple  阅读(229)  评论(0编辑  收藏  举报

导航