C++实现冒泡排序无法正确排序随机数组问题排查
排序输出异常问题排查
问题现象
对20个1-100的不重复随机数做排序时输出异常,所有调试日志均显示为sorted round: 0,最终数组未完成排序,还出现异常拼接值69 0,错误输出片段如下:
sorted round: 0: 87 sorted round: 0: 78 sorted round: 0: 16 sorted round: 0: 94 sorted round: 0: 36 sorted round: 0: 93 sorted round: 0: 50 sorted round: 0: 22 sorted round: 0: 63 sorted round: 0: 28 sorted round: 0: 91 sorted round: 0: 60 sorted round: 0: 64 sorted round: 0: 27 sorted round: 0: 41 sorted round: 0: 73 sorted round: 0: 37 sorted round: 0: 12 sorted round: 0: 69 84 78 16 87 36 93 50 22 63 28 91 60 64 27 41 73 37 12 69 0
原实现代码如下:
#include <stdio.h> #include <iostream> #include <algorithm> // for std::find #include <iterator> // for std::begin, std::end using namespace std; int main() { int random_array[20]; int i; int j; random_array[0]=rand()%(100-1+1)+1; for (i=1; i<20;) { j= rand()%(100-1+1)+1; bool exists; exists = find(begin(random_array), end(random_array), j) != end(random_array); if(!exists) { random_array[i]=j; i=i+1; } else { ; } } int size=20; i=0; j=0; int k =0; for (i; i < size; i++) { for (j; j < size - i; j++) { for(k; k<20; k++) { cout<<"sorted round: "<<j<<": "<<random_array[k]<<endl; } if (random_array[j] > random_array[j + 1]) { swap(random_array[j], random_array[j + 1]); } else { ; } } } for (i=0; i<20;i++) { cout<<random_array[i]<<endl; } return 0; }
根因定位
你怀疑的循环初始化位置确实是核心问题,具体错误点共4处:
- 循环变量未重置:
i/j/k三个循环变量均在循环外提前初始化,for循环的初始化语句为空。第一次内层循环执行完成后,j和k的值已经达到循环终止条件(j=20、k=20),后续外层i递增进入下一轮排序时,j和k不会从0重新开始遍历,直接跳过内层所有逻辑,这就是所有调试日志都停留在round 0的直接原因。 - 冒泡排序边界越界:相邻比较时
j+1最大只能取到数组最后一个有效下标19,因此内层j的遍历上界应为size - i - 1,原写法size -i会导致j=19时访问random_array[20],属于数组越界的未定义行为,是异常值69 0的来源之一。 - 随机数查重逻辑错误:填充数组时,下标
i之后的内存还未写入有效值,属于未初始化的垃圾值,原写法用find遍历整个数组(长度20)查重,会把未初始化的垃圾值也纳入比对范围,查重结果完全不可靠。 - 调试打印位置错误:打印全数组的k循环放在j的相邻比较循环内部,每做一次比较就打印全数组,加上k未重置的问题,第一次j=0遍历完k之后,后续所有j迭代都不会触发打印逻辑,日志完全不具备调试参考价值。
修复后代码
#include <iostream> #include <algorithm> #include <cstdlib> #include <ctime> using namespace std; int main() { // 增加随机数种子,避免每次运行生成完全一致的随机序列 srand((unsigned int)time(nullptr)); int random_array[20]; random_array[0] = rand() % 100 + 1; // 填充不重复随机数 for (int i = 1; i < 20;) { int val = rand() % 100 + 1; // 仅比对已经填充完成的0~i-1范围,不遍历未初始化的内存段 bool exists = find(random_array, random_array + i, val) != random_array + i; if (!exists) { random_array[i] = val; i++; } } int size = 20; // 冒泡排序:循环变量全部在for循环内初始化,避免残留值影响遍历 for (int i = 0; i < size; i++) { // 修正j的遍历上界,避免j+1访问越界 for (int j = 0; j < size - i - 1; j++) { if (random_array[j] > random_array[j + 1]) { swap(random_array[j], random_array[j + 1]); } } } // 输出最终排序结果 for (int i = 0; i < 20; i++) { cout << random_array[i] << endl; } return 0; }
内容的提问来源于stack exchange,提问作者DandyApe
相关产品推荐
相关产品推荐

