/* * 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 /* 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); /* comparison function to pass to qsort */ int compare(const void *e1, const void *e2); /* main program */ int main(int argc, char *argv[]) { int * data; /* will point to dynamically allocated array */ int count; int seed; char *endptr; /* get count, seed from command-line arguments */ if (argc != 3) { printf("usage %s count seed\n", argv[0]); return EXIT_FAILURE; } count = strtol(argv[1], &endptr, 10); if (*endptr != '\0') { printf("usage %s count seed\n", argv[0]); return EXIT_FAILURE; } seed = strtol(argv[2], &endptr, 10); if (*endptr != '\0') { printf("usage %s count seed\n", argv[0]); return EXIT_FAILURE; } if ((count <= 0) || (seed <= 0)) { printf("values must not be negative\n"); return EXIT_FAILURE; } /* allocate space for array */ if ((data = malloc(sizeof(data[0]) * count)) == NULL) { printf("unable to allocate space for %d values\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]), &compare); } /* comparison function to pass to qsort */ int compare(const void *e1, const void *e2) { int *i1 = (int *) e1; int *i2 = (int *) e2; if (*i1 < *i2) return -1; else if (*i1 > *i2) return 1; else return 0; }