【发布时间】:2014-10-26 14:01:09
【问题描述】:
我正在尝试制作通用冒泡排序功能。它允许用户编写自己的比较和交换函数。我为 int 类型实现了交换和比较函数,但是当我运行下一个数组的代码时: {3, 5, 8, 9, 1, 2, 4, 7, 6, 0} ,我得到: 0 0 84214528 2312 1 2 4 7 6 0。为什么会这样?
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
int compInt(void *a, void *b) // FUNCTION FOR COMPARE INT
{
if (*(int*)(a) > *(int*)(b)) { return false; } // IF FIRST INT > SECOND INT (WRONG ORDER) RETURN FALSE
return true; // RIGHT ORDER -> RETURN TRUE
}
我认为问题出在 swapInt 中。
void swapInt(void *a, void *b) // FUNCTION FOR SWAP INT
{
int aux; // TEMPORARY VARIABLE, IT STORAGES VALUE OF *(int*)(a)
aux = *(int*)(a);
*(int*)(a) = *(int*)(b); // a value is now equal to b value
*(int*)(b) = aux; // b has value of aux
}
void bubbleSort(void *address, int len, int (*comp)(void *a, void *b), void (*swap)(void *a, void *b)) // bubble sort function allow to user to write it's compare and swap function
{
int newlen;
while (len != 0) {
newlen = 0;
for (int i = 1; i < len; i++) {
if (!comp(address + i - 1, address + i)) {
swap(address + i - 1, address + i);
newlen = i;
}
}
len = newlen;
}
}
int main()
{
int array[] = {3, 5, 8, 9, 1, 2, 4, 7, 6, 0}; // CREATE AN ARRAY OF INT
int len = 10; // DECLARE IT LEN
void *address; // VOID POINTER TO ARRAY
address = array;
bubbleSort(address, len, &compInt, &swapInt); // SORT IT
for (int i = 0; i < len; ++i) {
printf("%d ", array[i]); // PRINT IT
}
return 0;
}
感谢您的帮助!
【问题讨论】:
-
你需要将元素大小作为参数传递给函数,并将
address + i替换为address + i * elementSize,否则你得到的地址将指向数组元素的中间。 -
不要定义
true和false宏,最好包含<stdbool.h>并使用bool。 -
@mephi42 , elementSize 将是 int 吗?如果我声明:void bubbleSort(void *address, int len, int elementSize, int (*comp)(void *a, void *b), void (*swap)(void *a, void *b)) 我打电话像这里:bubbleSort(address, len, sizeof(int), &compInt, &swapInt); ,答案是错误的。
-
我会在标准 qsort 函数之后为您的函数建模,它使用
size_t。 -
@mephi42 ,非常感谢!
标签: c pointers function-pointers void-pointers bubble-sort