// This file defines the implementation of the generic sorting function bubble_sort.

#include "bubble_sort.h"
#include <stdbool.h>  // for bool
#include <string.h>   // for memcpy

/* This is a generic function to swap two variables of the same type, given
 * pointers to the two variables and the size of each variable, in bytes.
 */
void swap(void *a, void *b, int elem_size_bytes) {
    char temp[elem_size_bytes];
    memcpy(temp, a, elem_size_bytes);
    memcpy(a, b, elem_size_bytes);
    memcpy(b, temp, elem_size_bytes);
}

/* This is a generic bubble sort function to sort an array of any type.
 * It accepts a comparison function as a parameter to properly compare elements. */
void bubble_sort(void *arr, size_t n, size_t elem_size_bytes, int (*cmp_fn)(void *, void *)) {
    while (true) {
        bool swapped = false;

        for (size_t i = 1; i < n; i++) {
            void *p_prev_elem = (char *)arr + (i - 1) * elem_size_bytes;
            void *p_curr_elem = (char *)arr + i * elem_size_bytes;
            if (cmp_fn(p_prev_elem, p_curr_elem) > 0) {
                swapped = true;
                swap(p_prev_elem, p_curr_elem, elem_size_bytes);
            }
        }

        if (!swapped) {
            return;
        }
    }
}