From 77f00f67f1a6b17cd59c561ab0a0c3587a11f327 Mon Sep 17 00:00:00 2001 From: nasdev-cmd Date: Thu, 29 Apr 2021 17:35:44 +0200 Subject: [PATCH] chore(C): Add bubble sorting (#269) --- algorithms/C/README.md | 1 + algorithms/C/sorting/bubble-sort.c | 60 ++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 algorithms/C/sorting/bubble-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 2ea6a755..13a70766 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -15,6 +15,7 @@ - [Double Ended Queue using array](queues/double-ended-queue-using-array.c) ## Sorting +- [Bubble Sort](sorting/bubble-sort.c) - [Merge Sort](sorting/merge-sort.c) - [Insertion Sort](sorting/insertion-sort.c) diff --git a/algorithms/C/sorting/bubble-sort.c b/algorithms/C/sorting/bubble-sort.c new file mode 100644 index 00000000..3e59e4b1 --- /dev/null +++ b/algorithms/C/sorting/bubble-sort.c @@ -0,0 +1,60 @@ +//bubble sort +#include +#include + +void swap(int *value1, int *value2); + +void bubble_sort(int array[], int array_size) +{ + for(int i = 0; i < array_size; i++) + { + for(int j = 0; j < array_size - 1; j++) + { + if(array[j] > array[j+1]) + { + swap(&array[j], &array[j+1]); + } + } + } +} + +void swap(int *value1, int *value2) +{ + int temp = *value1; + *value1 = *value2; + *value2 = temp; +} + +int main() +{ + int array_size; + do{ + printf("Input the size of the array: "); + scanf("%d", &array_size); + }while(array_size <= 1); + + int *array = (int*)malloc(sizeof(int)*array_size); + for(int i = 0; i < array_size; i++) + { + printf("Input an integer: "); + scanf("%d", &array[i]); + } + + bubble_sort(array, array_size); + + printf("Sorted array: [ "); + for(int i = 0; i < array_size; i++) + { + printf("%d ", array[i]); + } + printf("]\n"); + return 0; +} + +/* + * Input the size of the array: 5 + * Input 5 integers: [ 28, 17, 2, 5, 43 ] + * Output: Sorted array: [ 2, 5, 17, 28, 43 ] + * + * Time complexity: O(n^2) + */