/*---------------------------------------------------------------------
   An example of the use of the standard qsort() function
   Here the array being sorted is an array of doubles
   but the same basic technique can be used for arrays of any type.
   This code is derived from an example in the second edition of
   the book "C by Dissection", by Kelly and Pohl
 ---------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 11	/* size of the array */

/* Declarations of functions in this file */
static int compare(const void *vptr1, const void *vptr2);
static void fill_array(double *array, int n);
static void print_array(const double *array, int n);

int main(void)
{
	double arr[N];

	fill_array(arr, N);
	print_array(arr, N);
	qsort(arr, N, sizeof(double), compare);
	print_array(arr, N);
	return 0;
}

static int compare(const void *vptr1, const void *vptr2)
{
	const double	*ptr1, *ptr2;
	double		val1, val2;

	ptr1 = (const double *)vptr1;   /* ptr1 points to one of the doubles */
	ptr2 = (const double *)vptr2;   /* ptr2 points to the other double */
	val1 = *ptr1;    /* val1 is one of the double values to be compared */
	val2 = *ptr2;    /* val2 is the other double value to be compared */

	if (val1 == val2)
		return 0;
	else
		return (val1 > val2 ? 1 : -1);
}

static void fill_array(double *array, int n)
{
	int	i;

	srand(time(NULL));	/* use the current time as a seed for rand() */
	for (i = 0; i < n; i++)
	{
		/* each value is a random number between 0 and 100 */
		array[i] = (rand() % 1001) / 10.0;
	}
}

static void print_array(const double *array, int n)
{
	int	i;

	
	for (i = 0; i < n; i++)
	{
		if (i % 6 == 0)
			printf("\n");
		printf("%12.1f", array[i]);
	}
	printf("\n");
}

