/*
* 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
*/
double 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] = ((double) (random() % 100)) / 23.0;
}
/*
* 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("%6.3f ", 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 are done correctly, so the
* compiler does not complain
*
* also, the previous one didn't take doubles into account
* this one does, and makes sure dblcmp returns an int, as
* required
*/
int dblcmp(const void *x, const void *y)
{
return((int) (*(const double *)x - *(const double *)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(double), dblcmp);
/* 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. |