我正在研究算法。明年我要去大学学习计算机科学,所以我想在开课前学习一些东西。
目前我正在研究冒泡排序算法及其行为。
我在 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/