#include <stdio.h> void qsort(void * base, int num, int width, int (*comp)(const void *, const void *)); void sort(char * lo, char * hi, int (*comp)(const void *, const void *), int width); char * partition(char * lo, char * hi, int (*comp)(const void *, const void *), int width); void swap(char * a, char * b, int width); int mycomp(const void * p1, const void * p2); int main(void) { int i; int a[10] = {5, 3, 2, 9, 12, 6, 7, 10, 11, 1}; qsort(a, 10, 4, mycomp); for (i = 0; i < 10; i++) printf("%d ", a[i]); printf(" "); return 0; } int mycomp(const void * p1, const void * p2) { const int * a1 = (const int *) p1; const int * a2 = (const int *) p2; if (*a1 < *a2) return -1; else if (*a1 == *a2) return 0; else return 1; } void qsort(void * base, int num, int width, int (*comp)(const void *, const void *)) { char * lo = (char *) base; char * hi = (char *) base; hi += (num - 1) * width; sort(lo, hi, comp, width); } void sort(char * lo, char * hi, int (*comp)(const void *, const void *), int width) { char * p; if (lo >= hi) return; p = partition(lo, hi, comp, width); sort(lo, p - width, comp, width); sort(p + width, hi, comp, width); } char * partition(char * lo, char * hi, int (*comp)(const void *, const void *), int width) { char * i = lo; char * j = hi; while (i <= j) { do { i += width; if (i == hi) break; } while ((*comp)(i, lo) < 0); while (1) { if ((*comp)(j, lo) <= 0) break; j -= width; } if (i <= j) swap(i, j, width); } swap(j, lo, width); return j; } //swap one byte at a time void swap(char * a, char * b, int width) { char tmp; while (width--) { tmp = *a; *a++ = *b; *b++ = tmp; } }