/* * demonstrate the use of qsort by sorting an array * of random numbers * * Matt Bishop, ECS 36A, Fall 2019 */ #include #include /* * number of numbers to generate */ #define NUMFLOAT 30 /* * supposedly declared in stdlib.h, but not on this system * generate a random number between 0 and RAND_MAX inclusive * (RAND_MAX is defined in stdlib.h!) */ long int random(void); /* * the list of random numbers */ float list[NUMFLOAT], plist[NUMFLOAT]; /* * initialize the array with random numbers between 0 and 999 * inclusive */ void fillup(void) { int i; /* counter in a for loop */ /* put random numbers into the array */ for(i = 0; i < NUMFLOAT; i++){ list[i] = (float) random() / (float) (RAND_MAX / 100.0); plist[i] = list[i]; } } /* * print the array of random numbers */ void prlist(void) { int i; /* counter in a for loop */ /* print the array 10 numbers per line */ for(i = 0; i < NUMFLOAT; i++){ printf("%6.2f\t%6.2f\n", plist[i], list[i]); } } /* * qsort comparison function: return <0, 0, >0 * depending on whether the first integer pointed to * is less than, equal to, or greater than the second * integer pointed to * * note this takes pointers to the things to be sorted * the pointers here are done correctly, so the * compiler does not complain */ int intcmp(const void *x, const void *y) { float fx, fy; fx = *(float *) x; fy = *(float *) y; if (fx > fy) return(1); if (fx < fy) return(-1); return(0); } /* * the main routine to pull this together */ int main(void) { /* initialize the array */ fillup(); /* print it so user can see contents are out of order */ prlist(); /* separator to make it easier to see the unsorted and sorted */ printf("------------------\n"); /* now sort the array */ qsort(list, NUMFLOAT, sizeof(float), intcmp); /* print it out */ prlist(); /* bye! */ return(0); }