/* * demonstrate the use of qsort by sorting an array * of random numbers * * Matt Bishop, ECS 36A, Fall 2019 */ #include <stdio.h> #include <stdlib.h> /* * 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 */ int list[100]; /* * 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 < 100; i++) list[i] = (int) random() % 1000; } /* * 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 < 100; i++){ printf("%6d ", list[i]); if (i % 10 == 9) putchar('\n'); } } /* * 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 don't match the qsort prototype * (they should be const void *), so the compiler * complains -- and it's the way thing are usually * written. see qsort2.c for the right way to declare * the parameters and coerce them into the right types * for subtraction */ int intcmp(int *x, int *y) { return(*x - *y); } /* * 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, 100, sizeof(int), intcmp); /* print it out */ prlist(); /* bye! */ return(0); }
|
ECS 36A, Programming & Problem Solving Version of April 2, 2024 at 12:13PM
|
You can get the raw source code here. |