我正在尝试通过使用指针来实现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;
}
输出是相同的向量而没有排序。 (抱歉我的英文)
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *x, const void *y){
int a = *(const int *)x;
int b = *(const int *)y;
return a < b ? -1 : (a > b);
}
void swap(void *a, void *b, size_t type_size) {
void *tmp = malloc(type_size);
memcpy(tmp, a, type_size);
memcpy(a, b, type_size);
memcpy(b, tmp, type_size);
free(tmp);
}
void bubbleSort(void *base, size_t length, size_t type_size, int (*compar)(const void*, const void*)) {
int i, j;
for (i = 0; i < length - 1; ++i) {
for (j = i+1; j < length; ++j){
char *data_i = (char*)base + type_size * i;
char *data_j = (char*)base + type_size * j;
if(compar(data_i, data_j) > 0)
swap(data_i, data_j, type_size);
}
}
}
int main() {
int vet[] = {1, 2, 5, 7, 6, 1, 3, 2, 9, 15, 14, 20};
bubbleSort(vet, sizeof(vet)/sizeof(*vet), sizeof(*vet), cmp);
int i;
for (i = 0; i < sizeof(vet)/sizeof(*vet); i++) {
printf("%d\n", vet[i]);
}
return 0;
}
答案 1 :(得分:0)
当我在我的机器上运行上面的代码时,我得到了SIGSEGV
。然后我发现你的代码中有很多错误。
首先,你的swap
函数实际上什么也没做!您将两个指向数组元素的指针传递给该函数。您只是交换以前指向的地址。它没用。它可以用许多不同的方式编写。我更喜欢以下内容:
void swap(void* a, void* b) {
//get the int pointers...
int* t_a = (int*)a;
int* t_b = (int*)b;
//now change the values in them...
int tmp = *t_a;
*t_a = *t_b;
*t_b = tmp;
}
我首先将它们投放到int
的原因是,为void*
分配值毫无意义。
来到bubbleSort
代码,您认为base[i]
在您的代码中引用了什么?它不是数组中ith
元素的值。它是一个双指针,base[i]
实际上是指向指向其他数组的ith
指针。
由于此处只有一个数组,因此base[0]
是我们唯一有效的地址。如果你试图引用其他指针,那么它是SIGSEGV
,我在运行代码之前就已经预料到了。
你需要做的是,首先得到一个指针指向数组的第一个元素。(比如说ptr
)。现在ptr
只不过是我们的初始数组。然后使用它。
void bubbleSort(void** base, size_t length, int (*compar)(const void*, const void*)) {
int i, j;
int *ptr = &(*base);
for (i = 0; i < length; i++) {
for (j = 1; j < length; j++) {
if ((*compar)(&ptr[i], &ptr[j]) < 0) {
swap(&ptr[i], &ptr[j]);
}
}
}
}
希望这会有所帮助......