/* ------------------------------------------------------------------------ ** Use the quicksort algorithm to sort a file of numbers. ** Figures 21.14: Calling the quicksort() function. ** 21.6 : Setting up the data structures. (modified). ** 20.15: Input into an array. ** 20.16: Output from an array. ** ------------------------------------------------------------------------ */ #include "tools.h" typedef struct { float* data; int n; int max; } data_pack; #include "f15_quik.c" /* The quicksort algorithm. */ void setup( data_pack* spec, stream* infile, stream* outfile ); void get_data( data_pack* sortp, stream instream ); void quicksort( data_pack sort ); void print_data( data_pack sort, stream outstream ); /* ------------------------------------------------------------------ */ void main( void ) { stream in_str, out_str; /* Streams for input and output. */ data_pack sort; /* Specifications for sort. */ say( "\n Quicksort program." ); setup ( &sort, &in_str, &out_str ); get_data( &sort, in_str ); say( " %i data items read; ready to sort.\n", sort.n ); quicksort( sort ); say( " Data sorted; writing to output stream." ); print_data( sort, out_str ); bye(); } /* ------------------------------------------------------------------------ ** Read in the names of input and output files; open the files. ** Allocate memory for data. Errors are fatal. */ #define MAX 1000 void setup( stream* infile, stream* outfile, data_pack* spec ) { char filename[80]; printf( " Enter name of file containing data to sort: " ); scanf( "%79s", filename ); *infile = fopen( filename, "r" ); /* open input file in read mode */ if (*infile == NULL) fatal( " Error: couldn't open input file %s\n", filename ); printf( " Enter name of file for sorted data: " ); scanf( "%79s", filename ); *outfile = fopen( filename, "w" ); /* open output file in write mode */ if (*outfile == NULL) fatal( " Error: couldn't open output file %s\n", filename ); spec->max = MAX; /* Read up to MAX items. */ spec->n = 0; /* Currently empty. */ spec->data = malloc((MAX+1)*sizeof(float)); /* Array holds input + sentinel. */ if (spec->data == NULL) fatal( " Error: not enough memory for %i floats\n", MAX ); } /* ------------------------------------------------------------------------ ** Read max data values from instream and store in ary. */ void get_data( data_pack* sortp, stream instream ) { int stream_status; float* cursor = sortp->data; float const* end = cursor + sortp->max; /* off-board sentinel */ for( ; cursorn = cursor-sortp->data; /* Actual # of items read. */ } /* --------------------------------------------------------------------- ** Print array values, one per line, to selected stream. */ void print_data( data_pack sort, stream outstream ) { float* cursor = sort.data; const float* end = cursor + sort.n; /* an off-board sentinel */ for( ; cursor < end; ++cursor) { fprintf( outstream, " %.7g\n", *cursor ); } }