【发布时间】:2014-01-23 04:12:49
【问题描述】:
我正在尝试通过使用指向函数的指针在 c 中实现冒泡排序,但它不起作用。谁能帮我?代码如下:
#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\n", 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;
}
输出是相同的向量,没有排序。 (对不起我的英语)
【问题讨论】:
-
使用你的调试器,卢克。
标签: c pointers function-pointers void-pointers