/* * Program to test sort function: * Generate a random sequence of N integers, sort them, and check * that the sort succeeded. * This version gets N from a command-line argument and uses malloc() to get * space for the array. It sorts using library function qsort(). */ #include #include /* function declarations */ void fill_with_random(int data[], int size); void sort(int data[], int size); void check_sorted(int data[], int size); /* comparison function to pass to qsort */ int compare(const void *elem1, const void *elem2); /* * main program */ int main(int argc, char* argv[]) { int N; char* endptr; /* get number of elements to sort */ if (argc < 2) { fprintf(stderr, "usage: %s numToSort\n", argv[0]); return EXIT_FAILURE; } N = strtol(argv[1], &endptr, 10); if (*endptr != '\0') { fprintf(stderr, "usage: %s numToSort\n", argv[0]); return EXIT_FAILURE; } /* allocate space for array */ int * data = malloc(sizeof(*data) * N); if (data == NULL) { fprintf(stderr, "could not allocate space for %d ints\n", N); return EXIT_FAILURE; } /* fill, sort, check as before */ fill_with_random(data, N); sort(data, N); check_sorted(data, N); /* free allocated space */ free(data); return EXIT_SUCCESS; } /* * fills data[0 .. size-1] with a random sequence of integers */ void fill_with_random(int data[], int size) { for (int i = 0; i < size; ++i) { data[i] = rand(); /* printf("%d\n", data[i]); */ } } /* print array */ void print(int a[], int a_size) { for (int i=0; i < a_size; ++i) { printf("%d\n", a[i]); } } /* check whether array is sorted and print sorted / not sorted */ void check_sorted(int data[], int size) { for (int i = 0; i < size-1; ++i) { if (data[i] > data[i+1]) { printf("not sorted\n"); return; } } printf("sorted\n"); } /* sort array */ void sort(int data[], int size) { qsort(data, size, sizeof(data[0]), &compare); } /* comparison function to pass to qsort */ int compare(const void *elem1, const void *elem2) { int *e1 = (int *) elem1; int *e2 = (int *) elem2; if (*e1 < *e2) return -1; else if (*e1 > *e2) return 1; else return 0; }