aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-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;
+}