【问题标题】:How to Sort a List with Bubble sort in C++如何在 C++ 中使用冒泡排序对列表进行排序
【发布时间】:2015-12-14 17:08:24
【问题描述】:

我有这门课:

class Elem
{
public:
    int x;
    Elem *nast;
};

我有一个默认构造函数,函数显示x。我做了十个元素列表,但是如何对这个按x排序的列表进行排序?

我试过了:

void Sortlinked_list(Elem *head)
{
    int ile = 0;
    Elem *cur;
    cur = head;
    while( cur->nast != NULL )
    {
        cur = cur->nast;
        ile++;
    }

    Elem* curr = head;
    Elem* next;
    int temp;

    for(int i = 0; i < ile; i++ )
    {
        while( curr && curr->nast )
        {

            next = curr->nast;
            while (next)
            {
                if (curr->show() > next->show())
                {
                    std::swap(next->nast, curr->nast);
                }
                next = next->nast;
            }
            curr = curr->nast;
        }
    }
}

但它不起作用。输出为:http://i.stack.imgur.com/vJrRK.png

如果有人可以帮助我解决这个问题?我花了 3 个小时,一无所获。

【问题讨论】:

  • 从未听说过大黄蜂排序...
  • @SergeyA see en.wikipedia.org/wiki/Bubble_sort 你指的是错字吗?
  • 是的,冒泡排序 xD 错误
  • @dekros 您可以编辑您的问题以使其更清晰。
  • 我猜大黄蜂排序的大部分条目都按正确的顺序排列,大约 95%,无论如何。老兄

标签: c++ sorting linked-list bubble-sort


【解决方案1】:

在我看来算法有问题。

考虑:

7 -> 3 -> 5

在第一个循环中,cur 指向 7,next 指向 3,因此将交换 nast 指针。

交换后cur-&gt;nast 将指向 5 而next-&gt;nast 指向 3 本身。所以链条断了,元素3就丢失了。

7 -> 5
3 -> 3

换句话说 - 仅仅交换 nast 指针是不够的。

【讨论】:

  • 加 1 用于解释正在发生的事情,并让 OP 找到解决方案
【解决方案2】:

这是一个简单的函数实现方法。该函数只是交换相邻元素的数据成员x

void sort( Elem * &head )
{
    Elem *first = head; 
    Elem *last = nullptr;

    while ( first && first->nast != last )
    {
        Elem *sorted = first->nast;
        for ( Elem *current = first; current->nast != last; current = current->nast )
        {
            if ( current->nast->x < current->x ) 
            {
                std::swap( current->nast->x, current->x );
                sorted = current->nast;
            }                
        }
        last = sorted;
    }

    head = first;
}

【讨论】:

    【解决方案3】:

    交换列表中的节点时出现问题。如果节点相邻,则旋转 3 个 next 指针,如果节点不相邻,则交换 2 对 next 指针。如果代码先交换指向要交换的节点的下一个指针,然后交换要交换的节点的下一个指针,两种情况都处理。

    如果其中一个节点是列表中具有头指针的第一个节点,则会出现问题。和/或列表中具有尾指针的最后一个节点。

    更简单的替代方法是使用两个列表(只需要第二个指向节点的指针,最初为 NULL)。从源列表中删除一个节点,并将其按顺序插入到第二个最初为空的列表中。

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2013-10-31
      • 2017-09-27
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多