jibzoiderz jibzoiderz - 4 months ago 17
C++ Question

Is this code a bubble sorting program?

I made a simple bubble sorting program, the code works but I do not know if its correct.

What I understand about the bubble sorting algorithm is that it checks an element and the other element beside it.

#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;



It is a bubblesort implementation. It just is a very basic one.

Two improvements:

  • the outerloop iteration may be one shorter each time since you're guaranteed that the last element of the previous iteration will be the largest.
  • when no swap is done during an iteration, you're finished. (which is part of the definition of bubblesort in wikipedia)

Some comments:

  • use better variable names (test2?)
  • use the size of the container or the range, don't hardcode 5.
  • using std::swap() to swap variables leads to simpler code.

Here is a more generic example using (random access) iterators with my suggested improvements and comments and here with the improvement proposed by Yves Daoust (iterate up to last swap) with debug-prints