【问题标题】:Bubble Sort - Swap Counter method冒泡排序 - 交换计数器方法
【发布时间】:2017-07-29 14:40:18
【问题描述】:

我正在研究算法。明年我要去大学学习计算机科学,所以我想在开课前学习一些东西。

目前我正在研究冒泡排序算法及其行为。

我在 YouTube 上观看了哈佛大学 CS50 课程发布的视频,我正在尝试遵循他们的伪代码。我已经在网上找到了使用 2 个 for 循环的冒泡排序算法。但是在我观看的视频中,他们使用了一个带有交换计数器的 while 循环和一个 for 循环。我真的很想按照他们的程序。你可以在这里观看视频:https://www.youtube.com/watch?v=Ui97-_n5xjo&index=13&list=PLhQjrBD2T3816xq7BHLh4Yj6-v0TnvsrT

这就是我所拥有的。

int main() {

    int numbers[7] = {2, 7, 6, 3, 1, 5, 4};

    int swapCounter = 1;
    int swaps = 0;
    int temp = 0;

    while (swapCounter != 0){
        for (int i = 0; i == 5; i = i + 1) {

            if (numbers[i] > numbers[i+1]) {
                temp = numbers[i];
                numbers[i] = numbers[i+1];
                numbers[i+1] = temp;
                swaps = swaps + 1;
            }
            swapCounter = swaps;
        }
    }

    printf("%d\n", numbers[0]);
    printf("%d\n", numbers[1]);
    printf("%d\n", numbers[2]);
    printf("%d\n", numbers[3]);
    printf("%d\n", numbers[4]);
    printf("%d\n", numbers[5]);
    printf("%d\n", numbers[6]);
}

我也用过调试器,发现程序卡在for循环中。

【问题讨论】:

  • 1) i == 5; 错误。 2)swapCounterswaps 需要重置每个内循环。
  • 我该怎么办?但我必须将数字 5 与 i 的值进行比较。这不是作业吧?
  • 点赞this
  • 还是不行。现在它卡在 if 语句中。
  • 你能解释一下不起作用吗?你看到link 的结果了吗?

标签: c algorithm sorting bubble-sort cs50


【解决方案1】:
while (swapCounter != 0){
    **swaps = 0;**
    for (int i = 0; i < 7 - 1; i = i + 1) {
        if (numbers[i] > numbers[i+1]) {
            temp = numbers[i];
            numbers[i] = numbers[i+1];
            numbers[i+1] = temp;
            swaps = swaps + 1;
        }
    }
    **swapCounter = swaps;**
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2012-07-14
    • 2012-07-05
    • 1970-01-01
    相关资源
    最近更新 更多