/* L-12 MCS 572 Mon 6 Feb 2012 : time_qsort.c
 * This modification of use_qsort allows the user to specify the
 * dimension and verbose level at the command line for wall clock
 * timing with the unix time command. */

#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 vb = 1;
   int n;
   if(argc > 1)
      n = atoi(argv[1]);
   else
   {
      printf("give n : ");
      scanf("%d", &n);
   }
   if(argc > 2) vb = atoi(argv[2]);
   srand(time(NULL));
   {
      double *a;
      a = (double*)calloc(n,sizeof(double));
      random_numbers(n,a);
      if(vb > 0)
      {
         printf("%d random numbers :\n",n);
         write_numbers(n,a);
      }
      clock_t tstart,tstop;
      tstart = clock();
      qsort((void*)a,(size_t)n,sizeof(double),compare);
      tstop = clock();
      printf("time elapsed : %.4lf seconds\n",
             (tstop - tstart)/((double) CLOCKS_PER_SEC));
      if(vb > 0)
      {
         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);
}

