#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* This program demonstrates using qsort with different comparison
* functions.
*/
/*
* This function compares two integers for sorting ascending.
*/
int intasc(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
/*
* This function compares two integers for sorting ascending.
*/
int intdesc(const void *a, const void *b)
{
return *(int *)b - *(int *)a;
}
/*
* This sorts the intgers so that the odd ones come first, and otherwise
* ascending.
*/
int intoddeven(const void *_a, const void *_b)
{
int a = *(int *)_a;
int b = *(int *)_b;
if((a & 1) && !(b & 1)) return -1; /* a is odd, b is even. a first */
if(!(a & 1) && (b & 1)) return 1; /* b is odd, a is even. b first */
return a - b;
}
/*
* This one compares strings to sort descending. The array being sorted
* will be an array of pointers to char. The null pointer is allowed, and
* it always sorts at end.
*/
int strord(const void *_a, const void *_b)
{
char *a = *(char **)_a;
char *b = *(char **)_b;
if(a == NULL && b == NULL) return 0;
if(a == NULL) return 1;
if(b == NULL) return -1;
return strcmp(b, a);
}
/*
* Print an array of ints.
*/
void prints(char *lab, int *ints, int size)
{
printf("%s: ", lab);
while(size--) printf("%d ", *ints++);
putchar('\n');
}
/*
* Run some sorts.
*/
main()
{
int intarr[] = { 14, 21, 12, 34, 119, 56, 2, 19, 41 };
int numints = (sizeof intarr) / (sizeof intarr[0]);
char *strarr[] = { "snakes", "fish", NULL, "rocks", "water", NULL,
"sheep", NULL, NULL, "dogs", "cats" };
int numstr = (sizeof strarr) / (sizeof strarr[0]);
int n;
qsort(intarr, numints, sizeof(int), intasc);
prints("ascending", intarr, numints);
qsort(intarr, numints, sizeof(int), intdesc);
prints("descending", intarr, numints);
qsort(intarr, numints, sizeof(int), intoddeven);
prints("peculiar", intarr, numints);
qsort(strarr, numstr, sizeof(char *), strord);
for(n = 0; n < numstr; ++n)
if(strarr[n]) printf(" %s\n", strarr[n]);
else printf(" [NULL]\n");
}