/* * Program to test sort function: * Generate a random sequence of N integers, sort them, and check * that the sort succeeded. * This version gets N and a seed for generating the random sequence * from command-line arguments, allocates space for the integers dynamically, * and uses library function qsort() for the sort. */ #include #include /* has EXIT_SUCCESS, EXIT_FAILURE */ /* function declarations -- see definitions (at end) for more comments */ void fill_with_random(int a[], int size); void sort(int a[], int size); void print(int a[], int size); int find_out_of_order(int a[], int size); int int_compare(const void * e1, const void * e2); /* main program */ int main(int argc, char *argv[]) { /* get count, seed from command-line arguments */ if (argc != 3) { printf("usage %s count seed\n", argv[0]); return EXIT_FAILURE; } int count; int seed; char *endptr; count = strtol(argv[1], &endptr, 10); if (*endptr != '\0') { printf("usage %s count seed\n", argv[0]); return EXIT_FAILURE; } if ((count < 1) ) { printf("count must at least 1\n"); return EXIT_FAILURE; } seed = strtol(argv[2], &endptr, 10); if (*endptr != '\0') { printf("usage %s count seed\n", argv[0]); return EXIT_FAILURE; } if ((seed <= 0)) { printf("seed must not be negative\n"); return EXIT_FAILURE; } /* allocate space for array dynamically */ /* int data[MAX_COUNT]; */ int * data = malloc(count * sizeof(data[0])); if (data == NULL) { printf("cannot get space for %d ints\n", count); return EXIT_FAILURE; } /* fill with random data, sort, check, as before */ srand(seed); fill_with_random(data, count); /* uncomment if you want to print */ /* print(data, count) */ sort(data, count); /* uncomment if you want to print */ /* print(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); } /* free array */ free(data); return EXIT_SUCCESS; } /* fill array with randomly generated data */ void fill_with_random(int a[], int size) { for (int i = 0; i < size; ++i) { a[i] = rand(); } } /* print array */ void print(int a[], int size) { for (int i=0; i < size; ++i) { printf("%d\n", a[i]); } } /* * 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; } /* sort array */ void sort(int a[], int size) { qsort(a, size, sizeof(a[0]), &int_compare); } /* comparison function for sort */ int int_compare(const void * e1, const void * e2) { const int * i1 = (const int *) e1; const int * i2 = (const int *) e2; if (*i1 < *i2) return -1; else if (*i1 > *i2) return 1; else return 0; }