Here is my answer. This is essentially the same as the answer of VladimirFromUa (a recursive option for sorting bubbles), but instead of making a fixed number of runs, additional runs are only performed if he finds that the array was reordered in the previous run.
Another couple of differences below:
1. The parameter indexing the starting point in the array was reset by shifting the address of the array in recursive calls. 2. Checking "if (first <last && last> 0)" in Vlad or "if (--p_length == 1)" in my code is better done before a recursive call, which will lead to an array of length equal to 1, since this is one calling a call on the stack.
I added code to read input from the command line, and for convenience I printed both unsorted and sorted arrays.
#include <stdio.h> #include <stdlib.h> #include <assert.h> typedef enum { FALSE, TRUE } boolean_t; void swap_int(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } boolean_t sort_array(int p_array[], int p_length) { boolean_t result; if (p_array[0] > p_array[1]) { swap_int(p_array, p_array + 1); result = TRUE; } else { result = FALSE; } if (--p_length == 1) { return result; } result |= sort_array(p_array + 1, p_length); if (result) { sort_array(p_array, p_length); } return result; } void print_array_int(int p_array[], int p_length) { int n; for (n = 0; n < p_length - 1; n++) { printf("%d, ", p_array[n]); } printf("%d\n", p_array[n]); } int main(int argc, char **argv) { int *array; int array_length = argc - 1; int n; array = malloc(array_length * sizeof(*array)); for (n = 0; n < array_length; n++) { sscanf(argv[n + 1], "%d", array + n); } printf("\nUnsorted array:\n"); print_array_int(array, array_length); sort_array(array, array_length); printf("\nSorted array:\n"); print_array_int(array, array_length); return 0; }
Ashley
source share