簡體   English   中英

如何在C ++中使用氣泡排序對列表進行排序

[英]How to Sort a List with Bubble sort in C++

我有這個課:

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個小時,什么也沒做。

在我看來算法有問題。

考慮:

7 -> 3 -> 5

在第一個循環中, cur指向7, next指向3,因此將交換nast指針。

交換之后, cur->nast將指向5,而next->nast指向3。 因此,鏈條斷開,元素3丟失。

7 -> 5
3 -> 3

換句話說-僅交換nast指針是不夠的。

這是函數實現的一種簡單方法。 該函數只是交換相鄰元素的數據成員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個下一個指針,如果節點不相鄰,則交換2對下一個指針。 如果代碼交換了要先指向要交換的節點的下一個指針,然后交換了交換后要交換的節點的下一個指針,則兩種情況都將得到處理。

然后,如果其中一個節點是列表中具有頭指針的第一個節點,就會出現問題。 和/或列表中具有尾指針的最后一個節點。

一個更簡單的選擇是使用兩個列表(只需要第二個指向節點的指針,最初是NULL)。 從源列表中刪除一個節點,然后按順序將其插入第二個最初為空的列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM