【发布时间】: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 循环的第一次迭代之后,即使你做了排序也完成了仅通过您的链接列表一次。
-
不知道怎么改进。 -- 如果你看一下升序和降序代码,有什么区别?它是一个字符,
<和>。弄清楚如何摆脱代码重复(提示:创建一个单独的函数,当给定两个项目时,如果在排序时第一个项目在第二个项目之前,则返回true)。 -
恕我直言,您可以通过将双重链接列表转换为二叉树来改进其排序。
-
您可能想阅读How to Ask。
标签: c++ visual-studio c++11 bubble-sort