【发布时间】:2016-09-01 08:50:38
【问题描述】:
我做了一个简单的冒泡排序程序,代码有效但不知道是否正确。
我对冒泡排序算法的理解是它检查一个元素和它旁边的另一个元素。
#include <iostream>
#include <array>
using namespace std;
int main()
{
int a, b, c, d, e, smaller = 0,bigger = 0;
cin >> a >> b >> c >> d >> e;
int test1[5] = { a,b,c,d,e };
for (int test2 = 0; test2 != 5; ++test2)
{
for (int cntr1 = 0, cntr2 = 1; cntr2 != 5; ++cntr1,++cntr2)
{
if (test1[cntr1] > test1[cntr2]) /*if first is bigger than second*/{
bigger = test1[cntr1];
smaller = test1[cntr2];
test1[cntr1] = smaller;
test1[cntr2] = bigger;
}
}
}
for (auto test69 : test1)
{
cout << test69 << endl;
}
system("pause");
}
【问题讨论】:
-
并非如此。您必须重复内部循环,直到在循环期间没有交换。
-
你试过reading about bubble sort吗?那篇文章中的描述或伪代码是否与您的代码相符?如果不是,那不是冒泡排序。
-
尝试在循环期间打印出数组的状态以及您正在比较/交换的内容。它可以帮助您可视化您的代码在做什么,然后您可以更好地判断自己是否是冒泡排序。我在可视化排序算法时学习得最好
-
变量
cntr1和cntr2不是相互独立的;显然cntr2==cntr1+1是循环的变体。也许这个问题更适合代码审查。 -
冒泡排序的主要思想是每次迭代后,最重的元素位于数组的末尾。