簡體   English   中英

雙鏈表Bubblesort,反向方法現在被破壞

[英]Doubly Linked List Bubblesort, Reverse method now broken

因此,我最近更新了我的Bubblesort(按字母順序排序)以使用鏈接列表。

盡管現在我以前使用的反向方法打破了列表。 (如果我不先對單個列表氣泡進行排序,以前可以使用)

氣泡排序和交換。

void bubbleSort() {
    City *temp = NULL;
    City *current = head;
    while (current != NULL) { //for the rest in list
        if (current->getName().compare(current->next->getName()) > 0) { //compare distance
            if (current == head) {
                head = current->next;
            }
            swap(current, current->next);
        }
        current = current->next;
    }
}

交換

void swap(City* i, City* j) {
    if (i->previous)  i->previous->next = j;
    if (j->previous)  j->previous->next = i;
    if (i->next) i->next->previous = j;
    if (j->next) j->next->previous = i;
    City* temp;
    temp = i->previous;
    i->previous = j->previous;
    j->previous = temp;
    temp = i->next;
    i->next = j->next;
    j->next = temp;
}

這是現在損壞的反向列表。

void reverseList() {
    City *temp = NULL;
    City *current = head;

    while (current != NULL) {
        temp = current->previous;
        current->previous = current->next;
        current->next = temp;
        current = current->previous;

    }
    if (temp != NULL) {
        head = temp->previous;
    }
}

問題我從打破列表的氣泡排序中錯過了什么?

一個錯誤是您的冒泡排序實現。 由於氣泡排序的復雜度為O(n*n) ,因此應該對數據進行多次遍歷,其中n是要排序的項目數。

換句話說,您需要在bubbleSort執行while循環,直到您檢測到數據已排序為止。 可以通過使用僅在發生swap時設置的布爾標志來進行測試,或者僅使n通過數據來完成。

暫無
暫無

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

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