/* * sortfile.c - sort a file of numbers. To be called with two file pointers: * an input file and an output file. There is a maximum of 100 * numbers. * * Alan J Rosenthal, November 2000 */ #include #define MAXNUMS 100 void sortfile(FILE *in, FILE *out) { int a[MAXNUMS + 1], size, i; extern void sort(int *a, int size); /* * Read ints from "in", up to array limit or eof. * The assignment handout says it's ok to mistake non-numeric for EOF. * The array is one too big so that we can easily see if there are more * ints after. */ for (size = 0; size < sizeof a / sizeof a[0] && fscanf(in, "%d", &a[size]) == 1; size++) ; /* if we hit array limit, i.e. have exceeded MAXNUMS, then crab & exit */ if (size > MAXNUMS) { fprintf(stderr, "limit of %d values exceeded\n", MAXNUMS); exit(1); } /* sort and output */ sort(a, size); for (i = 0; i < size; i++) fprintf(out, "%d\n", a[i]); } /* bubblesort, from lecture */ void sort(int *a, int size) { int i, j, t; for (i = 0; i < size; i++) { for (j = 0; j < size - 1; j++) { if (a[j] > a[j+1]) { /* swap */ t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } }