1. 程式人生 > >C 語言泛型編程--quickSort實現

C 語言泛型編程--quickSort實現

ring log enum endif ide swa none ret sta

技術分享圖片
1 #ifndef _GENERICQUICKSORT_H_
2 #define _GENERICQUICKSORT_H_
3 void generic_swap(void * pa, void * pb, int typeSize);
4 void generic_qsort(void * pa, int elemSize, int typeSize,
5                             int (*cmp)(void *,void *));
6 #endif
generic_quick_sort.h 技術分享圖片
 1 #include <stdlib.h>
 2
#include <string.h> 3 #include <stdio.h> 4 #include "generic_quick_sort.h" 5 6 static void quick_sort(); 7 void generic_swap(void * pa, void * pb, int typeSize) 8 { 9 void * ptmp = malloc(typeSize); 10 memcpy(ptmp,pa,typeSize); 11 memcpy(pa,pb,typeSize); 12 memcpy(pb,ptmp,typeSize);
13 free(ptmp); 14 } 15 16 void generic_qsort(void *pa, int elemSize, int typeSize, 17 int (*cmp)(void *, void *)) 18 { 19 char *paa = (char*)pa; 20 quick_sort(paa,0,elemSize-1,typeSize,cmp); 21 } 22 23 static void quick_sort(char *paa, int beg, int end, int typeSize,
24 int (*cmp)(void *, void *)) 25 { 26 if(beg >= end) 27 return; 28 int mid = (beg+end)/2; 29 g_swap(paa + end * typeSize, paa + mid * typeSize, typeSize); 30 char *border = paa + end * typeSize; 31 int i = beg; 32 int j = beg; 33 for(; j < end; j++) 34 { 35 if(cmp(paa+j*typeSize, border) < 0){ 36 g_swap(paa+j*typeSize, paa+i*typeSize,typeSize); 37 i++; 38 } 39 } 40 g_swap(paa+j*typeSize, paa+i*typeSize,typeSize); 41 quick_sort(paa,beg,i-1,typeSize,cmp); 42 quick_sort(paa,i+1,end,typeSize,cmp); 43 }
generic_quick_sort.c 技術分享圖片
 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include "generic_quick_sort.h"
 5 #define PRINT_STUDENT(stu)     6     printf("name = %-10s, score = %-.2f\n",stu.name, stu.score)
 7 
 8 enum {LEN=10};
 9 typedef struct student{
10     char name[LEN];
11     double score;
12 }student;
13 
14 int cmp_stu(void *a, void *b);
15 
16 int main()
17 {    
18     student stu[5] = {
19         {"Linda", 76.14},
20         {"Angel",84.41},
21         {"Jim", 98.25},
22         {"Trump", 34.98},
23         {"Walle", 100}
24     };
25     generic_qsort(&stu,5,sizeof(student),cmp_stu);
26     for(int i = 0; i < 5; i++){
27         PRINT_STUDENT(stu[i]);
28     }
29     return 0;
30 }
31 
32 int cmp_stu(void *a, void *b)
33 {
34     student * pa = (student *)a;
35     student * pb = (student *)b;
36     if(pa->score < pb->score)
37         return -1;
38     else if(pa->score > pb->score)
39         return 1;
40     else return 0;
41 }
main

C 語言泛型編程--quickSort實現