From c723ad32bf1d5217b806cc1bdfbf50d70c6d66ce Mon Sep 17 00:00:00 2001 From: wael Date: Fri, 8 Oct 2021 23:09:11 +0300 Subject: [PATCH] Simplified and fixed the swap function, also fixed the bubble sort code. --- sorting_algorithms/bubble_sort/bubble_sort.c | 19 +++++-------------- utils/swap_void.c | 13 +++++++------ utils/swap_void.h | 2 +- 3 files changed, 13 insertions(+), 21 deletions(-) diff --git a/sorting_algorithms/bubble_sort/bubble_sort.c b/sorting_algorithms/bubble_sort/bubble_sort.c index b921942..3a1c878 100644 --- a/sorting_algorithms/bubble_sort/bubble_sort.c +++ b/sorting_algorithms/bubble_sort/bubble_sort.c @@ -22,29 +22,20 @@ void* bubble_sort(void* array, int (*comparison_function)(const void*, const voi /* Local variables. */ int i, j; - void *tmp; - - /* Allocate the buffer. */ - tmp = (void*) malloc(size); - if (tmp == NULL) - return NULL; /* Sort according to array, and comparison function. */ for (i = 0; i < length; i++) for (j = 0; j < length - 1; j++) { /* Check if to swap. */ - if (!comparison_function(array + j, array + j + 1)) { + if (!comparison_function(array + (j * size), array + ((j + 1) * size))) { /* Swap. */ - swap_void_ptr((array + j), (array + j + 1), tmp, size); - /* tmp = array[j]; - * array[j] = array[j + 1]; - * array[j + 1] = tmp; */ + swap_void_ptr(array + (j * size), array + ((j + 1) * size), size); + /*tmp = array[j]; + array[j] = array[j + 1]; + array[j + 1] = tmp;*/ } } - /* Free the buffer. */ - free(tmp); - /* Return the result. */ return array; } diff --git a/utils/swap_void.c b/utils/swap_void.c index 7657345..92c620a 100644 --- a/utils/swap_void.c +++ b/utils/swap_void.c @@ -1,14 +1,15 @@ /* Function to swap void* objects. */ -#include #include "swap_void.h" /* This function swaps void* objects. */ -/* Temp should be an allocated buffer, used to do the swap. */ /* Size should be > 0. */ /* Expect undefined behavior if conditions aren't met. */ -extern inline void swap_void_ptr(void *first, void *second, void *temp, size_t size) { +extern inline void swap_void_ptr(void *first, void *second, size_t size) { /* Swap. */ - memcpy(temp, first, size); - memcpy(first, second, size); - memcpy(second, temp, size); + char *a = (char*)first, *b = (char*)second, c; + while(size--) { + c = a[size]; + a[size] = b[size]; + b[size] = c; + } } diff --git a/utils/swap_void.h b/utils/swap_void.h index 6275e6f..04d9986 100644 --- a/utils/swap_void.h +++ b/utils/swap_void.h @@ -4,6 +4,6 @@ #include /* This function is used to swap void* objects. */ -extern inline void swap_void_ptr(void *first, void *second, void *temp, size_t size); +extern inline void swap_void_ptr(void *first, void *second, size_t size); #endif //SWAP_VOID_H