【问题标题】:How to implement bubble sort in C++?如何在 C++ 中实现冒泡排序?
【发布时间】:2020-09-26 16:09:32
【问题描述】:

我尝试在单链表上实现冒泡排序(通过更改指针)。我想知道这个解决方案有什么问题。这似乎很清楚并且应该可以工作,但我是 C++ 的初学者,所以我想我在某个地方犯了我无法发现的错误。下面是代码:

#include <iostream>
using namespace std;

struct node{
    int value;
    node *next = nullptr;
};

void print(node* n){
    while(n){
        cout<< n->value << " ";
        n = n->next;
    }
    cout << endl;
}

void replace(node*& first, node* second){
    node* tmp = second->next;
    second->next = first;
    first->next = tmp;
    first = second;
}

void bubbleSortRecu(node*& head, int length){
    if(!head || !head->next || length == 1) return;
    node* n = head;
    int counter = length - 1;
    while(n->next && counter){
        if(n->value > n->next->value)
            // std::swap(n->value, n->next->value); // swaping values works fine
            replace(n, n->next);
        n = n->next;
        counter --;
    }
    bubbleSortRecu(head, --length);
}

int main(){

    node* list = new node{4};
    list->next = new node{3};
    list->next->next = new node{5};
    list->next->next->next = new node{1};
    list->next->next->next->next = new node{0};

    cout << "Original: ";
    print(list);

    cout << "Replaced: ";
    replace(list, list->next);
    replace(list->next->next->next, list->next->next->next->next);
    print(list);

    bubbleSortRecu(list, 5);
    cout << "After bubblesort: ";
    print(list);

    return 0;
}

我已经在列表的前两个和最后两个元素上测试了替换功能。有效。致电bubbleSortRecu(list, 5) 后,我的清单已损坏。这是输出:

Original: 4 3 5 1 0 
Replaced: 3 4 5 0 1 
After bubblesort: 3 4 5  

您能解释一下如何解决它以及我在哪里做错了吗?

【问题讨论】:

  • 您是否使用调试器查看出了什么问题?
  • 或者确实,如果您不想使用调试器,那么绝对经典的“在每一行上添加一个打印语句来说明上一行的结果是什么以及下一行将做什么”应该也可以工作。
  • 如果 cout 方法没有帮助,可能是时候获取一个调试器,比如 Visual Studio 中的调试器,您可以一次单步执行 1 行代码,查看每个步骤的变量和流程了解为什么您的算法没有达到您的预期。
  • 如果你提供一个工作示例会更容易帮助你
  • @Ethr 公平地说,使用打印语句的建议是非常糟糕的建议。您基本上花费了大量的手动工作来复制调试器已经自动执行的操作并进行更多控制。相反,花时间学习如何使用您的调试器(应该不会花很长时间)。

标签: c++ algorithm sorting bubble-sort


【解决方案1】:

实际上,您不交换节点,只交换指向下一个节点的指针。

特别是,您不要修改指向您尝试交换的节点的指针。

例如,如果

a -> b -> c -> d

如果你想交换bc,那么a 现在应该指向c,而不是b。而且c应该指向b等。

因此,而不是获得

a -> c -> b -> d

用你的方法,你得到:

a -> b -> d
c -> c

因此,链条断了。

一个简单的解决方法是简单地交换节点内的value,而不修改指针。

void replace(node* first, node* second){
    std::swap (first->value, second->value);
}

【讨论】:

  • 我仍然不明白为什么在 main 中这样调用 replace(list, list-&gt;next); 的替换可以正常工作,但是在函数 bubbleSortRecu 中调用它时却不是。我不想改变价值观。 std::swap 在我的代码中被注释掉只是为了表明我的函数有效(当replace 没有在内部使用时)。
  • 我没有注意到值的交换解决方案在评论中。我试图在帖子中详细说明为什么您的方法不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 2012-07-23
  • 2020-08-23
  • 2017-03-11
  • 2014-10-26
相关资源
最近更新 更多