Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
typedef uint8_t byte;
static int compInt(const void *x, const void *y) {
const int first = *(const int *)x;
const int second = *(const int *)y;
if (first < second) return -1;
if (first > second)
return +1;
else
return 0;
}
static int compDouble(const void *x, const void *y) {
const double first = *(const double *)x;
const double second = *(const double *)y;
if (first < second) return -1;
if (first > second)
return +1;
else
return 0;
}
void swap(byte *x, byte *y, size_t size) {
while (size-- > 0) {
byte tmp = *x;
*x++ = *y;
*y++ = tmp;
}
}
void bubbleSort(void *base, size_t num, size_t size,
int (*cmp)(const void *, const void *)) {
byte *pbBase = (byte *)base; // pbBase: pointer to byte base
num -= 1;
if (num)
for (size_t i = 0; i < num; i++)
for (size_t j = 0; j < num - i; j++)
if (cmp(pbBase + (j + 1) * size,
pbBase + j * size) < 0)
swap(pbBase + (j + 1) * size,
pbBase + j * size, size);
}
int main() {
const int SIZE = 3;
int i[SIZE] = {0, 1, -1};
double d[SIZE] = {1.2, -3.4, 5.6};
bubbleSort(i, SIZE, sizeof(int), compInt);
printf("%d %d %d\n", i[0], i[1], i[2]);
bubbleSort(d, SIZE, sizeof(double), compDouble);
printf("%lf %lf %lf\n", d[0], d[1], d[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.