【发布时间】:2021-02-23 07:14:56
【问题描述】:
我正在尝试编写一个简单的冒泡排序算法,但它不起作用。数组在最后打印时是不变的。
我在我的 IDE 上使用了调试工具,它告诉我第二个 for 循环没有增加,但我不知道为什么它没有增加。
我对学习 C++ 和一般算法还是很陌生,所以这方面的指针会很有帮助。
这是代码,非常感谢。
#include <iostream>
int main(){
int A[] = {13, 89, 43, 74, 45, 16};
int n = sizeof(A)/sizeof(*A);
for (int i=0; i<n; i++) { //pass through the algorithm n-1 times
int flag = 0;
for (int j=0; j<n-i-1; j++) { //optimise checks, avoid checking sorted part of array
if (A[j] > A[j+1]) {
int temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
flag = 1; //shows a swap happened
}
if (flag == 0) { //no swaps have occurred so the loop is over
break;
}
}
}
for (int i = 0; i < n; i++) {
std::cout << A[i] << " ";
}
return 0;
}
【问题讨论】:
标签: c++ algorithm bubble-sort