/* Name: qsort-example2.c Purpose: Illustrates the use of the qsort() library function Author: Bill Slough */ #include #include #include #define PER_LINE 5 int compare_ints(const void *p, const void *q); void display_ints(int x[ ], int n); void display_strings(char *x[ ], int n); int compare_strings(const void *p, const void *q); int main(void) { int values[ ] = {120, 150, 30, 10, 130, 20, 90, 110, 140, 70, 80, 60, 50, 40, 100}; int values_size = sizeof(values)/sizeof(int); char *elements[ ] = {"hydrogen", "lithium", "sodium", "potassium", "beryllium", "magnesium", "calcium", "strontium", "barium", "radium"}; int elements_size = sizeof(elements)/sizeof(char *); /* Process the integer array */ printf("Before sorting:\n"); display_ints(values, values_size); /* sort them */ qsort(values, values_size, sizeof(int), compare_ints); printf("\nAfter sorting:\n"); display_ints(values, values_size); /* Process the string array */ printf("\nBefore sorting:\n"); display_strings(elements, elements_size); /* sort them... */ qsort(elements, elements_size, sizeof(char *), compare_strings); printf("\nAfter sorting:\n"); display_strings(elements, elements_size); return 0; } /* compare two integer values */ int compare_ints(const void *p, const void *q) { /* Cast the input parameters into the specific types */ const int *p1 = (const int *) p; const int *q1 = (const int *) q; /* return negative, zero, or positive for <, ==, or > */ if (*p1 < *q1) return -1; else if (*p1 > *q1) return +1; else return 0; } /* output the n integer values of an array x */ void display_ints(int x[ ], int n) { int i; for (i = 0; i < n; i++) { printf("%3d |", x[i]); if ((i + 1) % PER_LINE == 0) printf("\n"); } } /* compare two string values */ int compare_strings(const void *p, const void *q) { /* Cast the input parameters into the specific types */ const char **p1 = (const char **) p; const char **q1 = (const char **) q; /* return negative, zero, or positive for <, ==, or > */ return strcmp(*p1, *q1); } /* output the n string values of an array x */ void display_strings(char *x[ ], int n){ int i; for (i = 0; i < n; i++) { printf("%12s |", x[i]); if ((i + 1) % PER_LINE == 0) printf("\n"); } }