c++ - 冒泡排序c++中的比较函数

标签 c++ compare bubble-sort

您好,我需要在冒泡排序算法中实现比较函数,但我不知道该怎么做。

比较函数:

int compareNumbers(const void *a, const void  *b)
{
    object *A = (object *)a;
    object *B = (object *)b;
    if(A->number > B->number)
        return 1;
    else if(A->number < B->number)
        return -1;
    else
        return 0;
}

和冒泡排序:

void bubble_sort(object tab[],int size_tab)
{
object temp;
for(int i=1; i<size_tab; i++)
{
    for(int j=0; j<size_tab - i; j++)
    {
        if(tab[j].number > tab[j+1].number)
        {               
            temp = tab[j];
            tab[j] = tab[j+1];
            tab[j+1] = temp;
        }

    }   
}

我不确定当我想实现冒泡排序时,行:

if(tab[j].number > tab[j+1].number)

应该消失。

最佳答案

尝试类似的东西

bool compareNumbers(const void* a, const void* b) {
    object* A = (object*) a;
    object* B = (object*) b;
    if (A->number <= B->number) {
        return true;
    } else {
        return false;
    }
}

然后更改 bubbleSort 参数以使其看起来像

void bubbleSort(object tab[], int size_tab, 
                bool(comparator*)(const void*, const void*))

现在您可以将指针作为 bubbleSort 函数的第三个参数传递给 compareNumbers 函数:

bubbleSort(a, n, &compareNumbers);

并在 bubbleSort 的实现中使用它:

void bubbleSort(object tab[], int size_tab, 
                bool(comparator*)(const void*, const void*)) {
    object temp;
    for (int i = 1; i < size_tab; i++) {
        for (int j = 0; j < size_tab - i; j++) {
            if (comparator(tab + j, tab + j + 1)) {               
                temp = tab[j];
                tab[j] = tab[j+1];
                tab[j+1] = temp;
            }
        }
    }
}

关于c++ - 冒泡排序c++中的比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547715/

相关文章:

c++ - _beginthread/ex C3861 - 找不到标识符

c++ - 使用 Media Foundation SDK 进行直播

java - Java中ArrayList中每个组的最小值

pandas - 使用 Pandas 比较两列中的值

javascript - 使用两个哈希表来识别 JavaScript 中的相似之处

C : Sorting a 2d array using bubblesort algorithm only works one-way

c++ - 如何在调用 return 后删除 [] 内存

c++ - (Qt C++)调整像素图大小并保持像素化?

java - 双链表中的冒泡排序 - 空指针错误

c++ - 如何使用冒泡排序对链表进行排序?