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 }