【问题标题】:C++ Bubble Sort Negative NumbersC++ 冒泡排序负数
【发布时间】:2014-09-21 00:25:37
【问题描述】:

我为整数创建了一个数组冒泡排序函数,该函数与正整数完美配合,但在使用负整数时会崩溃。初始显示功能有效,但随后就冻结了。我尝试了一个有符号的 int 数组,但无济于事。

我已经找遍了,但找不到其他人有这个确切的问题。

    int defaultArray[6] = { 12, -5, 21, -1, 15, 17 };
    int numElements = 6;

    int lastSwap;
    int searchEnd = numElements - 1;
    bool sorted = false;

    while (!sorted)
    {
        for (int i = 0; i < searchEnd; ++i)
        {
            // If the number in position i is larger than the number in the
            // position i + 1 then swap them

            if (defaultArray[i] > defaultArray[i + 1]) {
                int temp = defaultArray[i];
                defaultArray[i] = defaultArray[i + 1];
                defaultArray[i + 1] = temp;
                lastSwap = i + 1;
            }
        }

        // If the lastSwap is at position one we can conclude that the array is
        // sorted so if lastSwap isn't 1 move searchEnd and continue
        if (lastSwap != 1)
        {
            // Conclude that from lastSwap to the end of the array is sorted
            // searchEnd begins one position to the left of lastSwap
            searchEnd = lastSwap - 1;
        }
        else {
            sorted = true;
        }

【问题讨论】:

  • 你有点忘了描述问题。你只是说它“停止工作”。但是,这是什么意思?它会崩溃吗?它会永远循环吗?它会产生不正确的结果吗?
  • 这里没有你所有的代码。你最初在哪里设置lastSwap,你在你的(外)循环中设置在哪里?
  • 一方面,如果您的数组开始排序,lastSwap 保持未定义,searchEnd 也是如此。

标签: c++ arrays bubble-sort negative-number compare-and-swap


【解决方案1】:

您正在尝试优化您的算法减少searchEnd,我认为存在问题。我建议您保持searchEnd 不变。要确定数组是否已排序,请将 sorted 设置为 true 并开始 while 循环,如果发生交换,请将其更改为 false。例如:

while (!sorted) {
    sorted = true;
    for (int i = 0; i < searchEnd; ++i) {
        if (defaultArray[i] > defaultArray[i + 1]) {
            // swap
            sorted = false;
        }
    }
}

【讨论】:

  • 即使我离开了有效的优化。我仍然不明白为什么它会崩溃,但谢谢。
猜你喜欢
  • 2014-03-26
  • 2018-11-13
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2017-06-21
  • 2012-07-19
  • 2015-09-06
相关资源
最近更新 更多