1 #include <stdio.h>
2 #include <stdlib.h>
3
4 typedef int DataType;
5
6 //比较器
7 int mycmp(const void * a, const void *b);
8
9 //int (*compar)(const void *, const void *) 函数指针
10 void Sort(DataType * arr, int from, int to, int (*compar)(const void *, const void *));
11
12 void merge(DataType *arr, int from, int mid, int to, int (*compar)(const void *, const void *));
13
14 void printArray(DataType * arr, int n);
15
16 int main()
17 {
18 DataType arr[10] = {2,3,10,12,6,1,18,14,65,12};
19 printf("Befor sort:\n");
20 printArray(arr,10);
21 Sort(arr, 0, 9, mycmp);
22 printf("After sort:\n");
23 printArray(arr,10);
24 return 0;
25 }
26
27 void Sort(DataType * arr, int from, int to, int (*compar)(const void *, const void *))
28 {
29 if(from == to)
30 return;
31 DataType mid = (from + to)/2;
32 Sort(arr, from, mid, *compar);
33 Sort(arr, mid+1, to, *compar);
34 merge(arr, from, mid, to, *compar);
35
36 }
37
38 void merge(DataType * arr, int from, int mid, int to, int (*compar)(const void *, const void*))
39 {
40 int i = 0;
41 DataType * first1 = arr + from;
42 DataType * end1 = arr + mid + 1;
43 DataType * first2 = arr + mid + 1;
44 DataType * end2 = arr + to + 1;
45 DataType * temp = (DataType *)malloc((to - from + 1)*sizeof(DataType));
46 DataType * p = temp;
47 while((first1 != end1) && (first2 != end2))
48 *p++ = ((*compar)(first1, first2) ? *first1++ : *first2++);
49 if(first1 == end1)
50 {
51 while(first2 != end2)
52 *p++ = *first2++;
53 }
54 else
55 {
56 while(first1 != end1)
57 *p++ = *first1++;
58 }
59 p = temp;
60 for(int i = from; i <= to; i++)
61 arr[i] = *p++;
62 free(temp);
63 }
64
65 int mycmp(const void * a, const void *b)
66 {
67 const DataType * pa = (const DataType *)a;
68 const DataType * pb = (const DataType *)b;
69 if(*pa >= *pb)
70 return 1;
71 else
72 return 0;
73 }
74
75 void printArray(DataType * arr, int n)
76 {
77 for(int i = 0; i < n; i++)
78 printf("%d ", arr[i]);
79 printf("\n");
80 }