qsort4.c

/*
 * 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.4f ", 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
 *
 * the previous one works *except* when the magnitude
 * of the difference is less than 1 and not 0; this
 * fixes that problem
 */
int intcmp(const void *x, const void *y)
{
	double diff;
	
	diff = *(const double *)x - *(const double *)y;

	if (diff > 0) return(1);
	if (diff < 0) 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, 100, sizeof(double), intcmp);

	/* print it out */
	prlist();

	/* bye! */
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh