C 语言泛型编程--quickSort实现

Posted 黑马网仔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C 语言泛型编程--quickSort实现相关的知识,希望对你有一定的参考价值。

技术分享图片
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实现的主要内容,如果未能解决你的问题,请参考以下文章

泛型编程(模板)

c语言实行泛型hashmap

Go 语言泛型编程之切片

C语言,快速排序算法

C++-模板-泛型编程-函数模板-类模板

手撕C语言标准库qsort(自我实现简化高效版C风格泛型快排)