/* L-12 MCS 572 Mon 6 Feb 2012 : use_qsort.c
 * C provides an implementation of quicksort.
 * The prototype of qsort is
 * 
 * void qsort ( void *base, size_t count, size_t size,
 *              int (*compar)(const void *element1,
 *                            const void *element2) );
 * 
 * qsort sorts an array whose first element is pointed to by base
 *       and contains count elements, of the given size.
 *
 * The function compar returns -1 if element1 < element2,
 *                              0 if element1 == element2,
 *                             +1 if element1 > element2.
 * 
 * This program sorts a random sequence of doubles.*/

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

void random_numbers ( int n, double a[n] );
/* returns n random doubles in [0,1] */

void write_numbers ( int n, double a[n] );
/* writes the sequence a of n numbers to screen */

int compare ( const void *e1, const void *e2 );
/* compares two elements of any type, for use in qsort of stdlib,
 * returns -1 if e1 < e2, 0 if e1 == e2, +1 if e1 > e2.  */

int main ( int argc, char *argv[] )
{
   int n;
   printf("give n : ");
   scanf("%d", &n);
   srand(time(NULL));
   {
      double *a;
      a = (double*)calloc(n,sizeof(double));
      random_numbers(n,a);
      printf("%d random numbers :\n",n);
      write_numbers(n,a);
      qsort((void*)a,(size_t)n,sizeof(double),compare);
      printf("The sorted numbers :\n");
      write_numbers(n,a);
   }
   return 0;
}

void random_numbers ( int n, double a[n] )
{
   int i;
   for(i=0; i<n; i++)
      a[i] = ((double) rand())/RAND_MAX;
}

void write_numbers ( int n, double a[n] )
{
   int i;
   for(i=0; i<n; i++) printf("%.15e\n", a[i]);
}

int compare ( const void *e1, const void *e2 )
{
   double *i1 = (double*)e1;
   double *i2 = (double*)e2;
   return ((*i1 < *i2) ? -1 : (*i1 > *i2) ? +1 : 0);
}

