1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <stdio.h>
#include <string.h>
int compare(void *a, void *b) {
return (strcmp(*(char **)a, *(char **)b)) > 0;
}
void swap (void *a, void *b) {
char *temp = *(char **)a;
*(char **)a = *(char **)b;
*(char **)b = temp;
}
void bubble_sort(void *array, size_t num, size_t ptr_size,
int (*cmp)(void *, void *), void (*swp)(void *, void *)) {
int didSwap;
size_t temp;
do {
didSwap = 0;
for (temp = 0; (temp+1) < num; ++temp)
if ((*cmp)((int *)(array+(temp*ptr_size)), (int *)(array+(-~temp*ptr_size)))) {
(*swp)((int *)(array+(temp*ptr_size)), (int *)(array+(-~temp*ptr_size)));
didSwap = 1;
}
num = temp;
} while (didSwap);
}
int main ( void ) {
char *array[] = {"Florida", "Oregon", "California", "Georgia"};
bubble_sort(array, 4, sizeof (char *), compare, swap);
printf("{");
for ( int r = 0; r < 4; ++r ) printf(" %s", array[r]);
puts(" }");
return 0;
}
|