【问题标题】:Does this count as a valid bubble sorting function? If so, how could I improve it?这算作有效的冒泡排序功能吗?如果是这样,我该如何改进它?
【发布时间】:2020-11-27 06:07:29
【问题描述】:

我是排序算法的新手,所以现在我或多或少只是在尝试学习基础知识。这是我用 C++ 编写的,用于对字符串进行排序并按字母顺序返回它的字符。我相当有信心这算作冒泡排序,但我想得到专家的确认:)。我也想听听您对如何进一步改进它的看法?

bool inOrder(std::string s){
    for(int i = 0; i < s.length(); i++){
        int thisLetterNum = s[i];
        int nextLetterNum = s[i + 1];
        if(thisLetterNum > nextLetterNum){
            return false;
        }
    }
return true;
}
std::string alphabetSoup(std::string str) {
    std::string &result = str;
    while(!inOrder(result)){
        for(int i = 0; i < str.length(); i++){
            int thisLetterNum = str[i];
            int nextLetterNum = str[i + 1];
            if(thisLetterNum > nextLetterNum){
                result[i] = nextLetterNum;
                result[i + 1] = thisLetterNum;
            }
        }
    }
    return result;
}

谢谢!

【问题讨论】:

  • 我也想听听您对如何进一步改进它的看法? -- 改进冒泡排序就像改进泥三明治一样。完全使用不同的排序,因为冒泡排序是最糟糕的排序之一。
  • 顺便说一句,这一行:int nextLetterNum = s[i + 1]; 是该 for 循环的最后一次迭代的越界访问。
  • 保罗打败了我。出于同样的原因,您不会找到很多冒泡排序专家。没有人在介绍性计算机编程课程之外使用它。如果你已经获得了足够多的资格成为专家……嗯……哎哟。
  • 我认为 Donald Knuth(或其中一位自吹自擂的 CS 家伙)表示它甚至不应该在学校教授。
  • 如果可行,请进行代码审查:codereview.stackexchange.com

标签: c++ algorithm sorting bubble-sort


【解决方案1】:

是的,这是一种冒泡排序。

我还想听听您对如何进一步改进它的看法

i = length() - 1 时您有未定义的行为,因为您使用的是 str[i + 1],所以修复这是我建议的第一个改进。

您也可以减少迭代次数并跳过inOrder()。您可以通过记录您是否进行了交换来跟踪它是否正常。

例子:

std::string alphabetSoup(std::string str) {
    bool swapped;
    size_t ei = str.length();
    do {
        --ei; // you can decrease this each iteration since the last element will be in
              // the correct place after each iteration
        swapped = false;
        for(size_t i = 0; i < ei; ++i) {
            if(str[i + 1] < str[i]) {
                std::swap(str[i], str[i + 1]);
                swapped = true;
            }
        }
    } while(swapped);

    return str;
}

【讨论】:

    【解决方案2】:

    第三次改进。递减
    str.length() 每次通过 1。这将行为从 n^2 更改为二次 ((n * n) + n) / 2。这与前面的建议相结合,从根本上改进了交换排序 [冒泡排序的另一个名称]。不幸的是,它仍然不如其他排序方法,只是很容易编码。

    【讨论】:

    • 这实际上是我在回答中提出的两个建议之一 :-)
    猜你喜欢
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多