/* * 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 a selection sort. */ #include #include /* function declarations */ void fill_with_random(int nums[], int size); void sort(int nums[], int size); void sort_check(int nums[], int size); /* * 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 * nums = malloc(sizeof(*nums) * N); if (nums == NULL) { fprintf(stderr, "could not allocate space for %d ints\n", N); return EXIT_FAILURE; } /* fill, sort, check as before */ fill_with_random(nums, N); sort(nums, N); sort_check(nums, N); /* free allocated space */ free(nums); return EXIT_SUCCESS; } /* * fills nums[0 .. size-1] with a random sequence of integers */ void fill_with_random(int nums[], int size) { for (int i = 0; i < size; ++i) { nums[i] = rand(); /* printf("%d\n", nums[i]); */ } } /* * prints "sort succeeded" if nums[0 .. size-1] is in order, * "sort failed" if not */ void sort_check(int nums[], int size) { for (int i = 0; i < size-1 ; ++i) { if (!(nums[i] <= nums[i+1])) { printf("sort failed\n"); return; } } printf("sort succeeded\n"); } /* gets index of smallest element of nums[start .. size-1] */ int index_of_smallest(int nums[], int size, int start) { int smallest = start; for (int i = start+1; i < size; ++i) { if (nums[i] < nums[smallest]) smallest = i; } return smallest; } /* * sorts nums[0 .. size-1] */ void sort(int nums[], int size) { for (int i = 0; i < size-1; ++i) { int k = index_of_smallest(nums, size, i); if (k != i) { int temp = nums[k]; nums[k] = nums[i]; nums[i] = temp; } } }