[英]C++ Bubble sorting a Doubly Linked List
我知道冒泡排序可能不是最快的方法,但它是可以接受的。 我只是在將算法調整為數組中的雙鏈接列表時遇到問題。
我的雙鏈表有一個 int 類型和一個 string 類型來保存一個數字和一個單詞。 我的列表是用我寫的按字母順序排序的插入排序進行排序的,現在我需要按數字重新排序我的雙鏈表,從最大到最小。
我的麻煩點是如何運行這個循環,以便它被正確地徹底排序,而不僅僅是一次。
這是我到目前為止設法得到的:
void DblLinkedList::ReorderListNumeric()
{
dummy = new Node();
temphead = head;
temp = head->next;
while(tempTwo->next != NULL)
{
if(temp->wordCount < tempTwo->wordCount)
{
dummy->word = tempTwo->word;
dummy->wordCount = tempTwo->wordCount;
tempTwo->word = temp->word;
tempTwo->wordCount = temp->wordCount;
temp->word = dummy->word;
temp->wordCount = dummy->wordCount;
}
temp = tempTwo;
tempTwo = tempTwo->next;
}
}
我的麻煩點是如何運行這個循環,以便它被正確地徹底排序,而不僅僅是一次。
如果您已經有一個可以成功執行一次傳遞並且交換沒有問題的循環,那么相對有效地執行多次傳遞的常用方法是:
set swapped = true
while swapped:
set swapped = false
do your one pass, setting swapped to true whenever you swap
這避免了初學者總是會開始使用的天真的 n 2解決方案。
就是這樣。
您將swapped
設置為true
以便您最初進入列表,然后在循環內立即將其設置為false
。
你的單次將設置swapped
只有當交換發生。 如果在您的通行證中沒有發生交換,則對列表進行排序並退出循環。
如果發生任何交換,則設置swapped
標志,您將需要運行另一遍。 這是因為交換可能位於列表的末尾並使之前的訂單無效,例如:
Initial: 1 2 3 4 6 7 5
Pass1: 1 2 3 4 6 5<=>7 (swap)
Pass2: 1 2 3 4 5<=>6 7 (swap)
Pass3: 1 2 3 4 5 6 7 (no swap, so exit loop)
因此,假設您的代碼是正確的,請從以下內容開始:
void DblLinkedList::ReorderListNumeric() {
Node *ptr, *dummy = new Node();
// Zero or one element, no sort required.
if (head == NULL) return;
if (head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
ptr = head;
while (ptr->next != NULL) {
if (ptr->wordCount < ptr->next->wordCount) {
// Swapping, need another pass.
swapped = 1;
dummy->word = ptr->word;
ptr->word = ptr->next->word;
ptr->next->word = dummy->word;
dummy->wordCount = ptr->wordCount;
ptr->wordCount = ptr->next->wordCount;
ptr->next->wordCount = dummy->wordCount;
}
ptr = ptr->next;
}
}
}
使用 2 個循環對列表進行徹底排序(我不考慮這里的效率,因為目前這對您來說並不重要)。 所以像處理數組一樣用 2 個指針迭代列表 -
void DblLinkedList::ReorderListNumeric()
{
NODE* temphead = NULL; // assuming your list is made of NODEs
NODE* temp = NULL;
for(temphead = head; temphead && temphead->next != NULL; ++ temphead)
{
for(temp = temphead->next; temp && temp->next != NULL; ++temp)
{
if(temphead->wordCount < temp->wordCount)
{
std::string dummyWord = temp->word;
int dummyCount = temp->wordCount;
temp->word = temphead->word;
temp->wordCount = temphead->wordCount;
temphead->word = dummyWord;
temphead->wordCount = dummyCount;
}
}
}
}
順便說一句,當您只想交換值時,為什么要創建一個虛擬節點來交換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.