home *** CD-ROM | disk | FTP | other *** search
- /*
- // An implementation of the Quicksort algorithm written specifically
- // for sorting arrays of C integer data types
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <sys/times.h>
-
- #define X 5
- #define Y 100000
-
- static int ia[X][Y] ;
-
- /*
- // Use of macro preferred to function - more code but faster !!
- */
- #define SWAP(A,I,J) { int temp=A[I]; A[I]=A[J]; A[J]=temp; }
-
- static void
- rqs (int *ip, int lo, int hi)
- {
- int last ;
- int i ;
-
- if (lo < hi)
- {
- SWAP (ip, lo, hi) ;
-
- last = lo ;
-
- for (i = lo + 1 ; i <= hi ; ++i)
- if (ip[i] < ip[lo])
- {
- ++last ;
- SWAP (ip, last, i) ;
- }
-
- SWAP (ip, lo, last) ;
-
- rqs (ip, lo, last - 1) ;
- rqs (ip, last + 1, hi) ;
- }
- }
-
- static void
- qsort (int *ip, int nel)
- {
- rqs (ip, 0, nel - 1) ;
- }
-
- main ()
- {
- struct tms start ;
- struct tms finish ;
- int i ;
- int j ;
-
- /*
- // Set seed for srand48
- */
- srand48 ((long)getpid()) ;
-
- /*
- // Load random data
- */
- for (i = 0 ; i < X ; ++i)
- for (j = 0 ; j < Y ; ++j)
- ia[i][j] = lrand48 () ;
-
- /*
- // Get CPU time prior to sorting
- */
- times (&start) ;
-
- /*
- // Sort the arrays
- */
- for (i = 0 ; i < X ; ++i)
- qsort (ia[i], Y) ;
-
- /*
- // Get CPU time after sorting
- */
- times (&finish) ;
-
- printf ("%.4f seconds to sort\n"
- , (double)(finish.tms_utime - start.tms_utime) / CLK_TCK) ;
-
- /*
- // Show results on stdout
- for (i = 0 ; i < X ; ++i)
- for (j = 0 ; j < Y ; ++j)
- printf ("%d\n", ia[i][j]) ;
- */
-
- return 0 ;
- }
-