qsort example ============= #include #include #define M 32 /* size of a[] */ #define N 11 /* size of b[] */ #define decimal_part(x) (x - (int) x) #define random_char() (rand() % 26 + 'a') #define random_float() (rand() % 100 / 10.0) #define FILL(a, n, type) \ for (i = 0; i < n; ++i) \ a[i] = (*type == 'c') ? random_char() : random_float() #define PRINT(a, n, cntrl_string) \ for (i = 0; i < n; ++i) \ printf(cntrl_string, a[i]); \ putchar('\n') main() { char a[M]; float b[N]; int i; int lexico(void *, void *); int compare_decimal_part(void *, void *); FILL(a, M , "char"); PRINT(a, M, "%-2c"); qsort(a, M, sizeof(char), lexico); PRINT(a, M, "%-2c"); /* left justifed 2 positions */ printf("---\n"); FILL(b, N, "float"); PRINT(b, N, "%-6.1f"); qsort(b, N, sizeof(float), compare_decimal_part); PRINT(b, N, "%-6.1f"); } int lexico(void *vp, void *vq) { char *p = vp, *q = vq; return (*p - *q); } int compare_decimal_part(void *vp, void *vq) { float *p = vp, *q = vq, x; x = decimal_part(*p) - decimal_part(*q); return ((x == 0.0) ? 0 : (x < 0.0) ? -1 : +1); } Output ====== w f a z y z a z o h s n g h c x s f u b s n s n w f u j e l g t a a b c e f f f g g h h j l n n n o s s s s t u u w w x y z z z --- 2.2 1.5 4.0 8.5 2.2 7.9 0.4 6.5 6.6 5.9 2.4 4.0 2.2 2.2 0.4 2.4 8.5 1.5 6.5 6.6 5.9 7.9