/* --------------------------------------------------------------------- ** Selection Sort ** Figure 16.15: Main program for sorting. ** Figure 16.9: (Modified) Reading the data from a file. ** Figure 16.17: Writing the data to a file. ** Figure 16.18: Sorting by selecting the minimum. ** Figure 16.21: Finding a minimum element. ** --------------------------------------------------------------------- */ #include "tools.h" #define LENGTH 20 int read_file( float x[], int nmax ); void sort_data( float data[], int n ); void write_file( float data[], int n ); void main( void ) { int n; /* # of data items; will be <=LENGTH. */ float data_list[LENGTH]; /* An array for the data to be sorted. */ banner(); n = read_file( data_list, LENGTH ); printf( " %i items were read; beginning to sort.\n", n ); sort_data( data_list, n ); puts( " Data sorted, ready for output" ); write_file( data_list, n ); bye(); } /* ------------------------------------------------------------------------ */ int read_file( float x[], int nmax) { int k; /* subscript variable for loop */ char infile[80]; /* name of input file */ stream fin; /* stream for input file */ int flag; /* for fscanf() return value */ printf( " Name of input file: " ); scanf( " %79[^\n]", infile ); fin = fopen( infile, "r" ); if (fin == NULL) fatal( "\n Fatal error: cannot open %s", infile ); printf( " Reading data from %s.\n", infile ); for (k = 0; k < nmax; ) { /* Don't read beyond end of data array. */ flag = fscanf( fin, "%g", &x[k] ); if (flag == 1) ++k; /* all is well -- count the item. */ else if( feof(fin) ) break; /* no more data is available. */ else { /* bad data -- note, skip, & continue. */ say( " --- Bad data while reading slot %i: ", k ); clean_and_log( fin, stderr ); } } fclose( fin ); return k; } /* ------------------------------------------------------------------------ */ void write_file( float data[], int n ) { int k; /* Subscript variable for loop. */ stream fout; char filename[80]; printf( " Name of output file: " ); scanf( " %79[^\n]", filename ); fout = fopen( filename, "w" ); if (fout == NULL) fatal( " Fatal error: cannot open %s.", filename ); for (k = 0; k < n; ++k) { /* Don't print beyond end of data. */ fprintf( fout, " %7.2f\n", data[k] ); } fclose( fout ); } /* ------------------------------------------------------------------------ */ void sort_data( float data[], int n ) { int find_min( float data[], int begin, int n ); int start, where; float smallest; for (start = 0; start < n - 1; ++start) { where = find_min( data, start, n ); smallest = data[where]; data[where] = data[start]; data[start] = smallest; } } /* ------------------------------------------------------------------------ */ int find_min( float data[], int begin, int n ) { int finger = begin; int cursor; for (cursor = begin + 1; cursor < n; ++cursor) { if (data[cursor] < data[finger]) finger = cursor; } return finger; }