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:
parent
3a28a3b52d
commit
aa3eec06ba
@ -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²) |
|
@ -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
|
@ -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", ¤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;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user