1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat(solutions): add sorting-algorithms/c/bubble-sort

This commit is contained in:
Divlo 2021-06-29 22:12:13 +02:00
parent 3a28a3b52d
commit aa3eec06ba
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
3 changed files with 51 additions and 0 deletions

View File

@ -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²) |

View File

@ -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

View File

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include "bubble_sort.h"
int main() {
int *numbers = malloc(25000 * sizeof(int));
int current_number;
int index_input = 0;
while (scanf("%d", &current_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;
}