/* This program uses code from "Algorithms in C, Third Edition," * by Robert Sedgewick, Addison-Wesley, 1998. */ #include #define MAX_SIZE 10000 /* sort array S in ascending order. N is the number of elements in S. */ void selection(int S[], int N) { int i, j; for (i = 0; i < N; i++) { int min = i; for (j = i+1; j < N; j++) { if (S[j] < S[min]) { min = j; } } int temp = S[min]; S[min] = S[i]; S[i] = temp; } } /* usage: selection_sort input_file output_file * * reads a set of numbers from the input file, sorts them, * and saves them in sorted order to the output file. */ int main(int argc, char ** argv) { int numbers[MAX_SIZE]; int i, next_number, items_read; if (argc != 3) { printf("selection_sort input_file output_file\n"); return -1; } char * input_file = argv[1]; FILE * fp = fopen(input_file, "rb"); int counter = 0; while(1) { items_read = fscanf(fp, "%d", &next_number); if (items_read != 1) { break; } numbers[counter] = next_number; counter++; if (counter == MAX_SIZE) { break; } } fclose(fp); selection(numbers, counter); char * output_file = argv[2]; fp = fopen(output_file, "wb"); for (i = 0; i < counter; i++) { fprintf(fp, "%d\n", numbers[i]); } fclose(fp); printf("sorted %d numbers, the result is stored at file %s\n", counter, output_file); }