【问题标题】:Bubble Sort gives random placement [closed]冒泡排序提供随机放置[关闭]
【发布时间】:2015-12-17 14:13:46
【问题描述】:

我正在使用冒泡排序对 6 个租金值进行降序排序。 但是,它会不断输出随机分类的数据。我已经将它与其他冒泡排序进行了比较,但无法确定为什么我的排序不正确。

代码如下:

void sortArray(int *rent, int size) {

    bool swap;
    int temp;
    int count = 0;

    do
    {
        swap = false;
        for (; count < (size - 1); count++) {
            if (*(rent + count) < *(rent + count + 1))
            {
                temp = rent[count];
                *(rent + count) = rent[count + 1];
                *(rent + count + 1) = temp;
                swap = true;
            }
        }
    } while (swap);

    for (count = 0; count < size; count++)
        cout << *(rent + count) << " ";
    cout << "\n";

}

【问题讨论】:

  • 在一个小案例上使用你的调试器
  • 一旦你得到两个项目,其中第一个不小于第二个,swap 将保留为false,do...while 循环将退出,其余的的数组将保持未排序。
  • 为什么要交错使用指针和数组表示法?只会让自己的代码更难理解?
  • 关闭这个,太吵了。
  • 我在高中和大学时代见过很多冒泡排序。这看起来不像我见过的任何冒泡排序。是时候回归基本面了……

标签: c++ arrays sorting bubble-sort


【解决方案1】:

我知道每个人都对你的代码感到沮丧,但实际上它正在排序,所以振作起来。您唯一的错误是您没有在每次外循环迭代中重置计数器。这个工作正常,检查for循环头!

void sortArray(int *rent, int size) {

    bool swap;
    int temp;
    int count = 0;

    do
    {
        swap = false;
        for (count=0; count < (size - 1); count++) {
            if (*(rent + count) < *(rent + count + 1))
            {
                temp = rent[count];
                *(rent + count) = rent[count + 1];
                *(rent + count + 1) = temp;
                swap = true;
            }
        }
    } while (swap);

    for (count = 0; count < size; count++)
        cout << *(rent + count) << " ";
    cout << "\n";

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2021-08-15
    • 2011-11-22
    • 1970-01-01
    相关资源
    最近更新 更多