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

66 lines
1.9 KiB
C
Raw Normal View History

2021-09-06 16:29:37 +00:00
/* This file has the implementation of the function for bubble sort. */
/* Include guards + include statements. */
#ifndef BUBBLE_SORT_C
#define BUBBLE_SORT_C
#include <string.h>
#include "bubble_sort.h"
#endif /* BUBBLE_SORT_C */
/* Function implementation. */
/* Note that if the comparison function is NULL, then the regular comparison operator is used <. */
/* Note that if copy is set to 0, then the array is sorted in-place, otherwise a sorted copy
* is what gets returned (after allocation), leaving the original intact. */
/* 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. */
/* 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, const int copy) {
2021-09-06 16:29:37 +00:00
/* Sanity check. */
if (array == NULL)
return NULL;
/* Local variables. */
int i, j;
void **ptr, *tmp;
2021-09-06 16:29:37 +00:00
/* Check if to allocate a copy. */
if (copy) {
/* Allocate the array. */
ptr = (void**) malloc(length * sizeof(void*));
/* Check if the allocation failed. */
if (ptr == NULL)
return NULL;
/* Copy the arrays' contents. */
memcpy(ptr, array, length * sizeof(void*));
} else
ptr = array;
/* Sort according to ptr, and based on the employed comparison function. */
if (comparison_function != NULL)
for (i = 0; i < length; i++)
for (j = 0; j < length - 1; j++) {
/* Check if to swap. */
if (!comparison_function(ptr + j, ptr + j + 1)) {
/* Swap. */
tmp = ptr[j];
ptr[j] = ptr[j + 1];
ptr[j + 1] = tmp;
}
}
else
for (i = 0; i < length; i++)
for (j = 0; j < length; j++) {
/* Check if to swap. */
if (ptr[j] > ptr[j + 1]) {
/* Swap. */
tmp = ptr[j];
ptr[j] = ptr[j + 1];
ptr[j + 1] = tmp;
}
}
/* Return the result. */
return ptr;
}