我试图制作通用的冒泡排序功能。它允许用户编写自己的比较和交换功能。我为int类型实现了一个swap和compare函数,但是当我运行下一个数组的代码:{3,5,5,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;
}
感谢您的帮助!
答案 0 :(得分:4)
谢谢@ mephi42。这是更新版本。
问题出在您的bubbleSort
功能中。您应该添加address
,其偏移量乘以元素大小。
正确的代码应为:
void bubbleSort(void *address, int len, size_t ele_size, 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((char*)address + ele_size * (i - 1), (char*)address + ele_size * i)) {
swap((char*)address + ele_size * (i - 1), (char*)address + ele_size * i);
newlen = i;
}
}
len = newlen;
}
}
然后调用函数:
bubbleSort(address, len, sizeof(int), compInt, &swapInt);