【问题标题】:Bubble sort in double linked list [closed]双链表中的冒泡排序[关闭]
【发布时间】:2022-01-06 16:59:09
【问题描述】:
void sortTrain(TrainCar* head, bool ascending)
{
    TrainCar* current = head;
    int count = 1;
    int size = (getlength(head));
    if (ascending == 1)
    {
        for(int i = 0; i < size-1; i++)
        {
            while(current->next)
            {
                if((current->load) > ((current->next)->load))
                {
                    swapCar(head,count,count+1);
                }
                count++;
                current = current->next;
            }
        }
    }

    if (ascending == 0)
    {
        for(int i = 0; i < size-1; i++)
        {
            while(current->next)
            {
                if((current->load) < ((current->next)->load))
                {
                    swapCar(head,count,count+1);
                }
                count++;
                current = current->next;
            }
        }
    }
}

有人帮我解决这个问题吗? 我不知道如何改进它。 或者任何其他代码可以做同样的结果? 当布尔升序为真时升序, 否则,做降序。

【问题讨论】:

  • 有人帮我解决问题吗? 您应该告诉我们问题所在,而不是让我们自己解决问题。它没有正确排序吗?它会崩溃吗?会发生什么?
  • 我可以告诉你,在每个 while 循环结束时, current 将为 null 并且不会发生进一步的排序,所以在你的 for 循环的第一次迭代之后,即使你做了排序也完成了仅通过您的链接列表一次。
  • 不知道怎么改进。 -- 如果你看一下升序和降序代码,有什么区别?它是一个字符,&lt;&gt;。弄清楚如何摆脱代码重复(提示:创建一个单独的函数,当给定两个项目时,如果在排序时第一个项目在第二个项目之前,则返回 true)。
  • 恕我直言,您可以通过将双重链接列表转换为二叉树来改进其排序。
  • 您可能想阅读How to Ask

标签: c++ visual-studio c++11 bubble-sort


【解决方案1】:

您发布的代码中的主要错误是您没有在每次外循环迭代后重置currentcount,即尝试以下操作:

// ...

if (ascending == 1)
{
    for (int i = 0; i < size-1; i++)
    {
        TrainCar* current = head;
        int count = 0;
        while (current->next)
        {
            if ((current->load) > ((current->next)->load))
            {
                swapCar(head, count, count + 1);
            }
            count++;
            current = current->next;
        }
    }
}

// ...

如果swapCar 使用从零开始的索引,上述内容应该可以工作(我还对其进行了更改,使count 初始化为零而不是一:永远不要在 C 或 C++ 中使用从 1 开始的索引;它只是这样做令人困惑)。

但是,将swapCar 实现为获取索引是一个糟糕的设计。对swapCar 的每次调用都将在 O(n) 时间内执行,如果您知道这意味着什么的话。您已经有currentcurrent-&gt;next 坐在那里:只需交换它们的负载值,然后您甚至根本不需要维护count 变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-04
    • 2022-01-09
    • 2018-05-18
    • 1970-01-01
    • 2011-04-13
    • 2012-02-10
    • 2011-09-04
    相关资源
    最近更新 更多