diff --git a/sorting/bubble_sort_2.c b/sorting/bubble_sort_2.c index 9e3c8000..26bbb526 100644 --- a/sorting/bubble_sort_2.c +++ b/sorting/bubble_sort_2.c @@ -1,46 +1,87 @@ -#include -#include +/** + * @file + * @brief implementation of [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) algorithm + * @details + * worst-case: O(n^2) + * best-case: O(n) + * average-complexity: O(n^2) + + * @author Unknown author + * @author [Gabriel Fioravante](https://github.com/northernSage) + */ + +#include /// for rand() calls +#include /// for assert() +#include /// for boolean values: true, false + #define MAX 20 -#define TRUE 1 -#define FALSE 0 -int main() +/** + * @brief Bubble sort implementation + * @param array_sort the array to be sorted + * @returns void + */ +void bubble_sort(int* array_sort) { - int i, arraySort[MAX] = {0}, isSort = FALSE, changePlace; + bool is_sorted = false; - /* For example - Insertion random values in array to test - */ - - for (i = 0; i < MAX; i++) + /* keep iterating over entire array + * and swaping elements out of order + * until it is sorted */ + while (!is_sorted) { - arraySort[i] = rand() % 101; - } + is_sorted = true; - /* Algorithm of bubble methods */ - - while (isSort) - { - isSort = FALSE; - - for (i = 0; i < MAX - 1; i++) + /* iterate over all elements */ + for (int i = 0; i < MAX - 1; i++) { - if (arraySort[i] > arraySort[i + 1]) + /* check if adjacent elements are out of order */ + if (array_sort[i] > array_sort[i + 1]) { - changePlace = arraySort[i]; - arraySort[i] = arraySort[i + 1]; - arraySort[i + 1] = changePlace; - isSort = TRUE; + /* swap elements */ + int change_place = array_sort[i]; + array_sort[i] = array_sort[i + 1]; + array_sort[i + 1] = change_place; + /* elements out of order were found + * so we reset the flag to keep ordering + * until no swap operations are executed */ + is_sorted = false; } } } +} - /* See if it works */ +/** + * @brief Test implementations + * @returns void + */ +static void test() { + /* simple int array for testing */ + int array_sort[MAX] = {0}; - for (i = 0; i < MAX; i++) + /* populate our test array with + * random integer numbers */ + for (int i = 0; i < MAX; i++) { - printf("%d\n", arraySort[i]); + array_sort[i] = rand() % 101; } - return EXIT_SUCCESS; + /* sort array */ + bubble_sort(array_sort); + + /* check if array ir correctly ordered */ + for (int i = 0; i < MAX - 1; i++) + { + assert(array_sort[i] <= array_sort[i+1]); + } +} + +/** + * @brief Main function + * @returns 0 on exit + */ +int main() +{ + test(); // run self-test implementations + return 0; }