c - 使用链表进行冒泡排序

标签 c linked-list bubble-sort

我正在编写一个冒泡排序函数来对双向链表中的节点进行排序。我的功能非常接近工作,但我缺少一些简单的东西,我无法弄清楚。

void sort (struct lnode** head, void (*swapPtr) (struct lnode** head, struct lnode* n1, struct lnode* n2),
                            int(*comparePtr) (void* v1, void* v2)) {

struct lnode* next;
struct lnode* temp = *head;
int comp;
struct lnode* temp2;
int count = 0;

while (temp != NULL) {
    temp2 = nodeGetNext(temp);
    temp = temp2;
    count++;

}

temp = *head;
for(int i = 0; i < count; i++) {
    next = nodeGetNext(temp);


    comp = comparePtr(temp,next);
    if (comp == 1)
        swapPtr(head, temp, next);
    else if (comp == -1)
        swapPtr(head, next, temp);

    temp = nodeGetNext(next);
}


}

当我运行函数时,它只交换前两个节点。我猜我没有在 for 循环结束时正确设置温度。我尝试了几种不同的方法,但没有取得任何成功。如果有任何帮助,我将不胜感激!

最佳答案

您似乎只通过了一次列表。您需要不断遍历列表并不断交换,直到没有任何东西可交换为止。检查这个answer例如和Wikipedia详细的算法说明。

关于c - 使用链表进行冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811249/

相关文章:

java - 按字符串对链表进行排序

c - 压栈不插入新值 - C

c - C 程序中的搜索和排序?

c - 升序冒泡排序问题

c - 如何确定 fgets 是否在读取所有字母之前停止?

c - FAST_FUNC在busybox中做什么?

c - 一个整数在c中奇怪地递增

c++ - 循环依赖问题链表

arrays - 汇编语言中数组的冒泡排序

c - fopen 不能在 linux 中为名称中包含德语字符的文件工作