/*----------------------------------------------------------------------------- * HTBLA-Leonding / Class: 2IHIF *----------------------------------------------------------------------------- * Exercise Number: S05 * Title: Sorting support functions * Author: Marc Tismonar *----------------------------------------------------------------------------- * Description: * Basic support functions for sorting *----------------------------------------------------------------------------- */ #include "sorting.h" #include #include #include #include "bubble_sort.h" #include "insertion_sort.h" /** * This file provides some basic functions for sorting and value initialization. * * Implementation hints: * Either list variant OR array variant of functions is required! * * init_random: * Randomizer functions are provided by `stdlib.h` * * The randomizer must be initialized via `srandom(time(NULL));` once before it is used * Generate random values via function `random()` * 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; } }