我的麻烦点是如何运行这个循环,以便它得到正确彻底的排序,而不仅仅是一次。
如果您已经有一个循环可以成功执行一次传递并且交换也可以,那么相对有效地执行多次传递的通常方法是:
set swapped = true
while swapped:
set swapped = false
do your one pass, setting swapped to true whenever you swap
This avoids the naive n2 solution that beginners will invariably start with.
确实如此。
You set swapped
to true
这样您最初输入列表然后将其设置为false
立即,在循环内。
您的单次通行证将设置swapped
仅当发生交换时。如果您的传递中没有发生交换,则列表将被排序并退出循环。
If any交换发生时,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;
}
}
}