归并排序

 1 #include <stdio.h>
 2 #include <malloc.h>
 3 
 4 typedef int ElementType;
 5 
 6 void _Merge(ElementType *Array,ElementType *TmpArray,int LeftStart,int RightStart,int RightEnd)
 7 {
 8     int i;
 9     int ArrayLen = RightEnd - LeftStart + 1;
10     int LeftEnd = RightStart - 1;
11     int TmpArrayEnd = LeftStart;
12     
13     while(LeftStart <= LeftEnd && RightStart <= RightEnd)
14     {
15         if(Array[LeftStart] <= Array[RightStart])
16         {
17             TmpArray[TmpArrayEnd++] = Array[LeftStart++];
18         }
19         else
20         {
21             TmpArray[TmpArrayEnd++] = Array[RightStart++];
22         }
23     }
24     
25     while(LeftStart <= LeftEnd)
26     {
27         TmpArray[TmpArrayEnd++] = Array[LeftStart++];
28     }
29     while(RightStart <= RightEnd)
30     {
31         TmpArray[TmpArrayEnd++] = Array[RightStart++];
32     }
33     
34     //copy TmpArray back to Array
35     for(i = 0;i < ArrayLen;i ++,RightEnd --)
36     {
37         Array[RightEnd] = TmpArray[RightEnd];
38     }
39 }
40 
41 void _MSort(ElementType *Array,ElementType *TmpArray,int Left,int Right)
42 {
43     int Center;
44     
45     if(Left < Right)
46     {
47         Center = (Left + Right) / 2;
48         _MSort(Array,TmpArray,Left,Center);
49         _MSort(Array,TmpArray,Center+1,Right);
50         _Merge(Array,TmpArray,Left,Center+1,Right);
51     }
52 }
53 
54 void MergeSort(ElementType *Array,int ArrayLen)
55 {
56     ElementType *TmpArray;
57     
58     TmpArray = malloc(ArrayLen * sizeof(ElementType));
59     
60     _MSort(Array,TmpArray,0,ArrayLen-1);
61     free(TmpArray);
62 }
63 
64 int main()
65 {
66     ElementType TestArray[10] = {9,2,4,1,2,5,9,3,7};
67     MergeSort(TestArray,10);
68     int i;
69     for(i = 0;i < 10;i ++)
70     {
71         printf("%d ",TestArray[i]);
72     }
73     printf("
");
74     return 0;
75 }
原文地址:https://www.cnblogs.com/Asurudo/p/9427434.html