/** * Program to test sorting function (using array obtained with malloc): * * Generate array of N random values. * * Sort the array, counting comparisons. * * Check that the result is sorted. * * Input: Number of elements. * * Output: Whether sort worked, and the numbers of comparisons. */ #include #include /* ---- Function declarations ---- */ void test_and_print(int n); void generate_data(int n, int nums[]); int find_index_of_max(int nums[], int last, int *num_compares); void selection_sort(int n, int nums[], int *num_compares); void is_sorted(int n, int nums[]); /* ---- Main program ---- */ int main(void) { int n; printf("how many numbers?\n"); if ((scanf("%d", &n) != 1) || (n <= 0)) { printf("input not a positive number\n"); return EXIT_FAILURE; } test_and_print(n); return EXIT_SUCCESS; } /* ---- Function definitions ---- */ /* * Generate data (n elements), sort, check, and print results, as described */ void test_and_print(int n) { int *nums = malloc(sizeof(int) * n); if (nums == NULL) { printf("unable to allocate memory\n"); exit(EXIT_FAILURE); } int num_compares = 0; generate_data(n, nums); selection_sort(n, nums, &num_compares); printf("is it sorted? (no news is good news)\n"); is_sorted(n, nums); printf("number of comparisons: %d\n", num_compares); free(nums); } /* * Generate n elements and put in nums */ void generate_data(int n, int nums[]) { int i; for (i = 0; i < n; ++i) { nums[i] = rand(); } } /* * Find largest element in nums[0 .. last] and return its index. * (Also modify *num_compares.) */ int find_index_of_max(int nums[], int last, int *num_compares) { int max; /* index of maximum so far */ int i; max = 0; for (i = 1; i <=last; ++i) { if (nums[i] > nums[max]) max = i; *num_compares += 1; } return max; } /* * Sort nums (array of size n). */ void selection_sort(int n, int nums[], int *num_compares) { int last; int index_of_max; int temp; for (last = n-1; last > 0; --last) { index_of_max = find_index_of_max(nums, last, num_compares); /* exchange nums[index_of_max] and nums[last] */ temp = nums[index_of_max]; nums[index_of_max] = nums[last]; nums[last] = temp; } } /* * Check that nums (array of size n) is sorted. * Prints messages about anything not sorted. */ void is_sorted(int n, int nums[]) { int i = 0; for (i = 0; i < n-1; ++i) { if (nums[i] > nums[i+1]) printf("out of order at %d!\n",i); } }