From 3c87c0ee7119a7635fd787657e69eca266326a59 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Thu, 28 Jul 2022 15:58:33 +0530 Subject: add bubble sort --- bsort.c | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 bsort.c (limited to 'bsort.c') diff --git a/bsort.c b/bsort.c new file mode 100644 index 0000000..56f8969 --- /dev/null +++ b/bsort.c @@ -0,0 +1,75 @@ +#include + +void print_array(int array[], int len); +void buble_sort(int array[], int len); +void buble_sort_rec(int array[], int len); +void swap(int *to, int *from); + +int +main(void) +{ + int array[] = {4, 2, 1, 7, 8, 9, 6, 0, 3, 5}; + + print_array(array, sizeof(array)/sizeof(int)); + buble_sort(array, sizeof(array)/sizeof(int)); + print_array(array, sizeof(array)/sizeof(int)); + + return 0; +} + +void +print_array(int array[], int len) +{ + while (len--) + printf("%d, ", *array++); + + printf("\n"); +} + +void +buble_sort(int array[], int len) +{ + int active, len_cp = len; + + while (--len_cp) { + if (len_cp == len - 1) { + active = 0; + } + + if (array[len_cp] < array[len_cp - 1]) { + swap(&array[len_cp], &array[len_cp - 1]); + active = 1; + } + + if (len_cp == 1 && active) + len_cp = len; + } +} + + + +void +buble_sort_rec(int array[], int len) +{ + int active = 0, len_cp = len; + + while (--len_cp > 0) + if (array[len_cp] < array[len_cp - 1]) { + swap(&array[len_cp], &array[len_cp - 1]); + active = 1; + } + + if (active) + buble_sort(array, len); + else + return; +} + +void +swap(int *to, int *from) +{ + int buff = *to; + + *to = *from; + *from = buff; +} -- cgit v1.2.3