/* * Program to test sort function: * Generate a random sequence of N integers, sort them, and check * that the sort succeeded. Program prompts user to enter N. */ #include #include int num_compares = 0; /* function declarations */ void fill_with_random(int nums[], int size); void sort(int nums[], int size); void sort_check(int nums[], int size); int compare(const void *elem1, const void *elem2); /* * main program */ int main(void) { int N; int *nums; fprintf(stdout, "enter size of array\n"); if (scanf("%d", &N) != 1) { fprintf(stderr, "input not numeric\n"); return 1; } nums = malloc(sizeof(*nums) * N); if (nums == NULL) { fprintf(stderr, "could not allocate space for %d ints\n", N); return 1; } fill_with_random(nums, N); sort(nums, N); sort_check(nums, N); fprintf(stdout, "%d comparisons\n", num_compares); free(nums); return 0; } /* * fills nums[0 .. size-1] with a random sequence of integers */ void fill_with_random(int nums[], int size) { int i; for (i = 0; i < size; ++i) { nums[i] = rand(); } } /* * prints "sort succeeded" if nums[0 .. size-1] is in order, * "sort failed" if not */ void sort_check(int nums[], int size) { int i; for (i = 0; i < size-1 ; ++i) { if ( !(nums[i] <= nums[i+1])) { printf("sort failed\n"); return; } } printf("sort succeeded\n"); } /* * sorts nums[0 .. size-1] */ void sort(int nums[], int size) { qsort(nums, size, sizeof(nums[0]), compare); } /* * compares two elements of the array (for qsort) */ int compare(const void *elem1, const void *elem2) { int *e1 = (int *) elem1; int *e2 = (int *) elem2; ++num_compares; if (*e1 < *e2) return -1; else if (*e1 > *e2) return 1; else return 0; }