/** * Program to test sorting function: * * Generate array of N random values. * Sort the array, counting how many comparisons were performed. * (This isn't essential to doing the sort, but the results may * be interesting.) * Check that the result is sorted. * * Input: Number of elements. * Output: Whether sort worked, and the numbers of comparisons. */ #include #include /* Function declarations. (Comments with definitions, below main.) */ void fill(int nums[], int size); void sort(int nums[], int size); void check(int nums[], int size); /* Main program. */ int main(void) { int N; int * nums; /* get N from user */ printf("Enter how many numbers to generate and sort:\n"); if (scanf("%d", &N) != 1) { printf("Error -- not a number\n"); /* bail out of program with return code indicating error */ exit(EXIT_FAILURE); } /* try to get memory for array of N ints */ nums = malloc(sizeof(int) * N); if (nums == NULL) { printf("Error -- not enough memory for %d numbers\n", N); /* bail out of program with return code indicating error */ exit(EXIT_FAILURE); } /* fill with random numbers, sort, and check result */ fill(nums, N); sort(nums, N); check(nums, N); /* release allocated memory */ free(nums); /* return value indicates success (same as "return 0" but perhaps * more readable */ return EXIT_SUCCESS; } /* * Fill array with random numbers. * "size" is the size of array "nums". */ void fill(int nums[], int size) { int i; for (i = 0; i < size; ++i) { nums[i] = rand(); } } /* * Sort array and print number of comparisons done. (This isn't essential * to getting the array put in order, but results may be interesting.) * * "size" is the size of array "nums". */ void sort(int nums[], int size) { int i, j, temp; int comparisons = 0; /* bubble sort */ for (i = 0; i < size-1; ++i) { /* go through elements from 0 through size-1-i, switching pairs * that are out of order. * (why size-1-i? because the first time through we end up with * the last element in the right place, the next time through * with the last 2 elements in the right place, etc. */ for (j = 0; j < size-1-i; ++j) { ++comparisons; /* for each pair of adjacent elements, switch if out of * order */ if (nums[j] > nums[j+1]) { temp = nums[j]; nums[j] = nums[j+1]; nums[j+1] = temp; } } } printf("Sorting %d numbers required %d comparisons\n", size, comparisons); } /* * Check whether array is in order and print result. * "size" is the size of array "nums". */ void check(int nums[], int size) { int i; for (i = 0; i < size-1; ++i) { if (nums[i] > nums[i+1]) { printf("Sort failed -- numbers are not in order\n"); return; } } printf("Sort succeeded -- numbers are in order\n"); }