c - 冒泡排序 - 交换计数器方法

标签 c algorithm sorting bubble-sort cs50

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

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

我在 YouTube 上观看了哈佛大学 CS50 类(class)发布的视频,我正在尝试跟踪他们的伪代码。我已经在网上找到了使用 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 循环中。

最佳答案

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;**
}

关于c - 冒泡排序 - 交换计数器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45390507/

相关文章:

c - free( ) 时堆损坏

查找满足特定条件的最接近整数值的算法

c++ - 是否有一个标准算法来迭代一个范围?

C++ 对数字字符串数组进行排序 - 比较函数不起作用

c - 试图理解 C 指针、 block 和 go to 语句的问题

javascript - 如何在 Javascript 中循环十六进制?

mysql - mysql中的字母数字列自然排序,其中数据是字母、数字、特殊字符的任意组合

algorithm - 为什么计数排序不用于大输入?

c - 如何使用 C 中的特定头文件打印程序中使用的内置函数名称?

algorithm - AC-1 和 AC-3 算法的区别?