1
0
Fork 0

Simplified and fixed the swap function, also fixed the bubble sort code.

This commit is contained in:
wael 2021-10-08 23:09:11 +03:00
parent 233b303bff
commit c723ad32bf
3 changed files with 13 additions and 21 deletions

View File

@ -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;
}

View File

@ -1,14 +1,15 @@
/* Function to swap void* objects. */
#include <stdlib.h>
#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;
}
}

View File

@ -4,6 +4,6 @@
#include <string.h>
/* 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