aboutsummaryrefslogtreecommitdiff
path: root/bsort.c
diff options
context:
space:
mode:
authorsinanmohd <pcmsinan@gmail.com>2022-07-28 15:58:33 +0530
committersinanmohd <pcmsinan@gmail.com>2022-07-28 15:58:33 +0530
commit3c87c0ee7119a7635fd787657e69eca266326a59 (patch)
tree9889b4e4debf688a502f01a68d1c3574ac6f72c3 /bsort.c
parent6f9e88bee99e0fae4d7ec67022979501c7fa2b01 (diff)
add bubble sort
Diffstat (limited to 'bsort.c')
-rw-r--r--bsort.c75
1 files changed, 75 insertions, 0 deletions
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 <stdio.h>
+
+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;
+}