/* L-12 MCS 572 Monday 6 Feb 2006 use the qsort in stdlib.h
 * 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_sequence ( int n, double a[n] );
/* returns n random doubles in [0,1] */

void print_sequence ( 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;
   srand(time(NULL));
   printf("Give number of elements to sort : "); scanf("%d", &n);
   {
      double a[n];
      random_sequence(n,a);
      printf("The generated sequence :\n"); print_sequence(n,a);
      qsort((void*)a,(size_t)n,sizeof(double),compare);
      printf("The sorted sequence :\n"); print_sequence(n,a);
   }
   return 0;
}
void random_sequence ( int n, double a[n] )
{
   int i;
   for(i=0; i<n; i++) a[i] = ((double) rand())/RAND_MAX;
}
void print_sequence ( int n, double a[n] )
{
   int i;
   for(i=0; i<n; i++) printf(" %.15lf", a[i]);
   printf("\n");
}
int compare ( const void *e1, const void *e2 )
{
   double *i1 = (double*)e1;
   double *i2 = (double*)e2;
   return ((*i1 < *i2) ? -1 : (*i1 > *i2) ? +1 : 0);
}
