/* Name: qsort-example1.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); 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); /* 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); 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"); } }