/* * Program to sort integers read from a file and write results to a file: * * Input and output filenames are given by command-line arguments. * Maximum number of integers to allow is given by (compile-time) parameter * ARRAY_SIZE. */ #include #include /* has EXIT_SUCCESS, EXIT_FAILURE */ #define ARRAY_SIZE 10000 void sort(int a[], int size); int find_out_of_order(int a[], int size); /* main program */ int main(int argc, char* argv[]) { if (argc < 3) { fprintf(stderr, "usage %s infile outfile\n", argv[0]); return EXIT_FAILURE; } FILE* infile = fopen(argv[1], "r"); if (infile == NULL) { fprintf(stderr, "cannot open input file %s\n", argv[1]); return EXIT_FAILURE; } int data[ARRAY_SIZE]; int count = 0; int temp; while (fscanf(infile, "%d", &temp) == 1) { if (count < ARRAY_SIZE) { data[count++] = temp; } else { fprintf(stderr, "array size %d exceeded\n", ARRAY_SIZE); return EXIT_FAILURE; } } if (!feof(infile)) { fprintf(stderr, "invalid input at line %d\n", count+1); return EXIT_FAILURE; } fclose(infile); FILE* outfile = fopen(argv[2], "w"); if (outfile == NULL) { fprintf(stderr, "cannot open output file %s\n", argv[2]); return EXIT_FAILURE; } sort(data, count); int out_of_order = find_out_of_order(data, count); if (out_of_order < 0) { printf("sorted\n"); } else { printf("not sorted\n"); printf("first out-of-order element at index %d\n", out_of_order); } for (int i = 0; i < count; ++i) { fprintf(outfile, "%d\n", data[i]); } fclose(outfile); return EXIT_SUCCESS; } /* * check whether array is sorted: * returns index of first out-of-order element, or -1 if all are in order */ int find_out_of_order(int a[], int size) { for (int i = 0; i < size-1; ++i) { if (a[i] > a[i+1]) { return i; } } return -1; } /* get index of smallest element of a[start .. size-1] */ int index_of_smallest(int a[], int size, int start) { int smallest = start; for (int i = start+1; i < size; ++i) { if (a[i] < a[smallest]) smallest = i; } return smallest; } /* sort array (selection sort) */ void sort(int a[], int size) { for (int i = 0; i < size-1; ++i) { int k = index_of_smallest(a, size, i); if (k != i) { int temp = a[k]; a[k] = a[i]; a[i] = temp; } } }