diff --git a/sorting.c b/sorting.c index 1050fd3..a1aa8bc 100644 --- a/sorting.c +++ b/sorting.c @@ -32,5 +32,97 @@ * Limit random value to `MAX_VALUE` as defined in `config.h` */ +static int is_random_initialized = 0; + +/** + * Provides the name of the given sorting algorithm. + * + * @param algorithm The sorting algorithm + * @return The name of the algorithm. + */ +char* get_algorithm_name(SortingAlgorithm algorithm) { + switch (algorithm) { + case BUBBLE_SORT: + return "Bubble Sort"; + case INSERTION_SORT: + return "Insertion Sort"; + default: + return "Unknown Algorithm"; + } +} + +/** + * Initializes the given list with random elements. + * + * @param list The list to initialize. + * @param item_count The number of items to insert. + */ +void init_list_random(IntList list, int item_count) { + if (!list_is_valid(list)) { + return; + } + + if (!is_random_initialized) { + srandom(time(NULL)); + is_random_initialized = 1; + } + + list_clear(list); + + for (int i = 0; i < item_count; i++) { + int random_value = random() % (MAX_VALUE + 1); + list_insert(list, random_value); + } +} + +/** + * Prints the values stored in the given list. + * + * @param prefix The optional text to print before values are printed. + * @param list The list to dump. + */ +void print_list(char* prefix, IntList list) { + if (!list_is_valid(list)) { + return; + } + + if (prefix != NULL) { + printf("%s", prefix); + } + + printf("["); + for (int i = 0; i < list_get_size(list); i++) { + printf("%d", list_get_at(list, i)); + if (i < list_get_size(list) - 1) { + printf(", "); + } + } + printf("]\n"); +} + +/** + * Sorts the given list using the given sorting algorithm. + * + * @param list The list to sort. + * @param algorithm The sorting algorithm to use. + * @param criterion The pointer to the function that implements the sorting criterion. + * That function accepts two integer parameters and returns a boolean value. + */ +void sort_list(IntList list, SortingAlgorithm algorithm, criterion_fn criterion) { + if (!list_is_valid(list)) { + return; + } + + switch (algorithm) { + case BUBBLE_SORT: + bubble_sort_list(list, criterion); + break; + case INSERTION_SORT: + insertion_sort_list(list, criterion); + break; + default: + break; + } +}