From aa3eec06baf44a59b4899208649bef2ebe0acf66 Mon Sep 17 00:00:00 2001 From: Divlo Date: Tue, 29 Jun 2021 22:12:13 +0200 Subject: [PATCH] feat(solutions): add `sorting-algorithms/c/bubble-sort` --- .../solutions/c/bubble-sort/README.md | 7 ++++ .../solutions/c/bubble-sort/bubble_sort.h | 8 +++++ .../solutions/c/bubble-sort/solution.c | 36 +++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 challenges/sorting-algorithms/solutions/c/bubble-sort/README.md create mode 100644 challenges/sorting-algorithms/solutions/c/bubble-sort/bubble_sort.h create mode 100644 challenges/sorting-algorithms/solutions/c/bubble-sort/solution.c diff --git a/challenges/sorting-algorithms/solutions/c/bubble-sort/README.md b/challenges/sorting-algorithms/solutions/c/bubble-sort/README.md new file mode 100644 index 0000000..d44c3cb --- /dev/null +++ b/challenges/sorting-algorithms/solutions/c/bubble-sort/README.md @@ -0,0 +1,7 @@ +# sorting-algorithms/c/bubble-sort + +Created by [@Divlo](https://github.com/Divlo) on 29 June 2021. + +| Algorithm | Best Case | Average Case | Worst Case | +| ----------------------------------------------------------- | ----------- | ------------ | ----------- | +| [Bubble sort](https://wikipedia.org/wiki/Bubble_sort) | O(n) | O(n²) | O(n²) | diff --git a/challenges/sorting-algorithms/solutions/c/bubble-sort/bubble_sort.h b/challenges/sorting-algorithms/solutions/c/bubble-sort/bubble_sort.h new file mode 100644 index 0000000..743cec9 --- /dev/null +++ b/challenges/sorting-algorithms/solutions/c/bubble-sort/bubble_sort.h @@ -0,0 +1,8 @@ +#ifndef BUBBLE_SORT_H +#define BUBBLE_SORT_H + +void swap_numbers(int *value_1, int *value_2); + +void bubble_sort(int *numbers, const int length); + +#endif diff --git a/challenges/sorting-algorithms/solutions/c/bubble-sort/solution.c b/challenges/sorting-algorithms/solutions/c/bubble-sort/solution.c new file mode 100644 index 0000000..6ca962a --- /dev/null +++ b/challenges/sorting-algorithms/solutions/c/bubble-sort/solution.c @@ -0,0 +1,36 @@ +#include +#include + +#include "bubble_sort.h" + +int main() { + int *numbers = malloc(25000 * sizeof(int)); + int current_number; + int index_input = 0; + while (scanf("%d", ¤t_number) != EOF) { + numbers[index_input] = current_number; + index_input += 1; + } + bubble_sort(numbers, index_input); + for (int index = 0; index < index_input; index++) { + printf("%d\n", numbers[index]); + } + free(numbers); + return 0; +} + +void bubble_sort(int numbers[], const int length) { + for (int index_1 = 0; index_1 < length; index_1++) { + for (int index_2 = 0; index_2 < length - index_1 - 1; index_2++) { + if (numbers[index_2] > numbers[index_2 + 1]) { + swap_numbers(&numbers[index_2], &numbers[index_2 + 1]); + } + } + } +} + +void swap_numbers(int *value_1, int *value_2) { + int temporary = *value_1; + *value_1 = *value_2; + *value_2 = temporary; +}