1
0
Fork 0
C_lib/sorting_algorithms/bubble_sort/bubble_sort.c

42 lines
1.4 KiB
C

/* This file has the implementation of the function for bubble sort. */
/* Include guards + include statements. */
#ifndef BUBBLE_SORT_C
#define BUBBLE_SORT_C
#include <stdlib.h>
#include <string.h>
#include "bubble_sort.h"
#include "../utils/swap_void.h"
#endif /* BUBBLE_SORT_C */
/* Function implementation. */
/* Note that if the comparison function is NULL, then the function will quit. */
/* Note that the comparison function should return 1 if the second argument is larger than or
* equal to the first, otherwise zero. */
/* The array's length should be passed in the length argument. */
/* Size should match a single object's size, and should be > 0. */
/* The function returns a NULL pointer on error, caller must check! */
void* bubble_sort(void* array, int (*comparison_function)(const void*, const void*), const int length, size_t size) {
/* Sanity check. */
if (array == NULL || comparison_function == NULL || size <= 0)
return NULL;
/* Local variables. */
int i, j;
/* 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 * size), array + ((j + 1) * size))) {
/* Swap. */
swap_void_ptr(array + (j * size), array + ((j + 1) * size), size);
/*tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;*/
}
}
/* Return the result. */
return array;
}