直接给代码 原理就不啰嗦了;

View Code
 1 void OutPut(int *arr,int len)
 2 {
 3     for(int i=0; i < len; ++i)
 4     {
 5         cout<<arr[i]<<"  ";
 6     }
 7     cout<<endl;
 8 }
 9 //序列a1为两个有序的子序列,a1[s...m] 和 a[m+1,e]有序
10 // 把a1的两个有序子序列合并为一个有序数列a2
11 void Merge(int* a1,int* a2, int s, int m, int e)
12 {
13     int k,j;
14     for(k = s, j = m+1; s <= m && j <= e; ++k)
15     {
16         if(a1[s] < a1[j])
17         {
18             a2[k] = a1[s++];
19         }
20         else
21         {
22             a2[k] = a1[j++];
23         }
24      }
25     if(s <= m)
26     {
27         for(int i = 0; i <= m-s; ++i)
28         {
29             a2[k+i] = a1[s+i];
30         }
31     }
32     if(j <= e)
33     {
34         for(int l = 0; l <= e-j; ++l)
35         {
36             a2[k+l] = a1[j+l];
37         }
38     }
39 }
40 //归并排序里的Msort函数
41 void Msort(int* a1,int* a2,int b, int e)
42 {
43     int atmp[21];
44     int m;
45     if(b == e) a2[b] = a1[b];
46     else
47     {
48          m = (e + b)/2;
49         Msort(a1,atmp,b,m);
50         Msort(a1,atmp,m+1,e);
51         Merge(atmp,a2,b,m,e);
52     }
53 }
54 //归并排序入口
55 void MergeSort(int *arr,int len)
56 {
57     Msort(arr,arr,0,len-1);
58 }
59 int _tmain(int argc, _TCHAR* argv[])
60 {
61     int a[20]={-1,23,5456,21,784,12,46,89,21213,687,32,-12,8,0,123,-34,2332,33330,5674,1111};
62     HeapSort(a,20);
63 //    MergeSort(a,20);
64     OutPut(a,20);
65     return 0;
66 }

 

 

posted on 2012-09-11 16:20  TianMG  阅读(163)  评论(0编辑  收藏  举报