I'm trying to implement a bubble sort in c by using pointers to function but does not work. Can anyone help me? Here is the code:
#include <stdio.h>
#include <stdlib.h>
void bubbleSort(void** base, size_t length, int (*compar)(const void*, const void*));
int main(int argc, char* argv[]) {
int cmp(const void*, const void*);
int vet[] = {1, 2, 5, 7, 6, 1, 3, 2, 9, 15, 14, 20};
bubbleSort((void**) &vet, sizeof(vet)/sizeof(vet[0]), cmp);
int i;
for (i = 0; i < sizeof(vet)/sizeof(vet[0]); i++) {
printf("%d
", vet[i]);
}
return 0;
}
int cmp(const void* x, const void* y) {
return **((int* const*) x) - **((int* const*) y);
}
void bubbleSort(void** base, size_t length, int (*compar)(const void*, const void*)) {
int i, j;
void swap(void*, void*);
for (i = 0; i < length; i++) {
for (j = 1; j < length; j++) {
if ((*compar)(base[i], base[i]) < 0) {
swap(base[i], base [j]);
}
}
}
}
void swap(void* a, void* b) {
void* tmp = a;
a = b;
b = tmp;
}
The output is the same vector without sorting.
(Sorry for my English)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…