Bubble Sort Please help.

I have to sort random data with bubble sort and animation. I believe my below code is somewhat "ok"? But I would like to delay each line by asking user to press enter between each sort. (How to)
Also would like the program to print line before sorted, with numbers or (pass zero) and final comment would be line final sorted....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void BubbleSort(int a[],int p)
{
    cout<<"pass "<<p<<":";

    for(int i=0;i<10;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

int main()
{
    srand (time(0));
    int a[10];
    for(int i=0;i<10;i++)
    {
        a[i]=rand() % 100 + 1;
    }
    for(int i=0;i<10-1;i++)
    {
        for(int j =0; j<10-i-1;j++)
        {
            if(a[j]>a[j+1])
            {
                int t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }

         }
    BubbleSort(a,i);
    }
return 0;
}
I fixed my first question by inserting cin.ignore()
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void BubbleSort(int a[],int p)
{
cout<<"pass "<<p<<":";

for(int i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
cin.ignore();
cout<<endl;
}

I would like output to display
Array before sorting XXXXXXXX
Array being sorted XXXXXenter
XXXXenter
XXXXenter
XXXXenter
Array after being sorted XXXXX enter

how do I do that?
Hello studentlearningcplusplus,

Some things to help get you started.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using namespace std;

constexpr int MAXSIZE{ 10 };

void BubbleSort(int a[], int p)
{
    cout << "pass " << p << ":";

    for (int i = 0; i < MAXSIZE; i++)
    {
        cout << a[i] << " ";
    }

    cout << endl;
}

You can change "MAXSIZE" to anything you like, but I would keep the capital letters. It helps to remind you that it is a constant variable and can not be changed.

You call the function "BubbleSort", but all it does is print to the screen. It should be called "Print" or "Display" because that is what you actually do in the function.

If you want the function to sort then move the nested for loops in "main" to the function.

In your updated function you added cin.ignore();. Since you do not have a cin >> something; I am curios as to how this fixed a problem and what the problem was in the first place?

In "main" srand(static_cast<unsigned int>(time(nullptr))); is better written this way. "srand()" takes an "unsigned int" as its seed, but "time" does not return an "unsigned int". I believe from C++11 on "nullptr" is the better choice, but (0) and "NULL" still work. This video is worth watching to better understand the problems with using "rand()". https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int main()
{
    //srand(time(0));
    srand(static_cast<size_t>(time(nullptr)));

    int a[MAXSIZE];

    for (int i = 0; i < MAXSIZE; i++)
    {
        a[i] = rand() % 100 + 1;
    }

    for (int i = 0; i < MAXSIZE - 1; i++)
    {
        for (int j = 0; j < 10 - i - 1; j++)
        {
            if (a[j] > a[j + 1])
            {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
        }

        BubbleSort(a, i);
    }

You are good down to the sorting loops.

The outer for loop is OK. And notice the change I made.

The inner for loop is a problem as is the if statement. Just thinking about it 10 - i - 1 makes me think that as "i" increases "j" will not check the entire array. The other problem is "j" should start at "i" + 1 for (int j = i + 1. This way "i" is where you are at and "j" is the next element in the array. Then the if condition would be
(a[i] > a[j]). Now you are comparing 2 different elements of the array until the outer loop is finished. And since the outer loop stops 1 short of the end "j" will never go past the end of the array.
for (int j = i + 1; j < MAXSIZE; j++).

After that if you want to keep the function "BubbleSort" then move these for loops to that function and create a new function to print or display the array.

To your second post.

If you want the program to create the array then print out the unsorted array then tell the program to do so. The idea would be:
for loop to give the array numbers.
print array (unsorted array).
sort array.
print array (sorted array).

Other than testing there is no reason to print the array during the sort function.

At the end of main I use this code to pause the program before the window closes.
1
2
3
4
5
6
7
// A fair C++ replacement for "system("pause")". Or a way to pause the program.
// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
std::cout << "\n\n Press Enter to continue: ";
std::cin.get();

return 0;  // <--- Not required, but makes a good break point. 

Line 3 is commented out because there is nothing to ignore. Otherwise you would have to press "Enter" twice to end the program.

Andy
Thank you Andy,

Great feedback and lots of help.
Any way you can provide a couple lines of codes to explain how I can print results. I do need it for testing results.
At the momments each line prints
pass 0 : x x x x x x x xx
pass 1 : x x x x x xx x

I need feedback on how I could print a separate sentence for the first line and last line, but also include each pass.
Hello studentlearningcplusplus,

Sorry. It took a couple of times to finally understand what you wanted. I think.

I have a "main" that looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
    //srand(time(0));
    srand(static_cast<size_t>(time(nullptr)));

    int a[MAXSIZE];

    InitArray(a);

    std::cout << "\n      Unsorted array\n" << std::string(30, '-') << '\n';

    Print(a);

    BubbleSort(a);

    std::cout << "\n        Sorted array\n" << std::string(30, '-') << '\n';

    Print(a);

    return 0;
}


And the output looks like this:


      Unsorted array
------------------------------
8 39 19 74 82 80 95 94 48 29

pass 1: 8 39 19 74 82 80 95 94 48 29    Press Enter:
pass 2: 8 19 39 74 82 80 95 94 48 29    Press Enter:
pass 3: 8 19 29 74 82 80 95 94 48 39    Press Enter:
pass 4: 8 19 29 39 82 80 95 94 74 48    Press Enter:
pass 5: 8 19 29 39 48 82 95 94 80 74    Press Enter:
pass 6: 8 19 29 39 48 74 95 94 82 80    Press Enter:
pass 7: 8 19 29 39 48 74 80 95 94 82    Press Enter:
pass 8: 8 19 29 39 48 74 80 82 95 94    Press Enter:
pass 9: 8 19 29 39 48 74 80 82 94 95    Press Enter:

        Sorted array
------------------------------
8 19 29 39 48 74 80 82 94 95


There is a space after "Enter:" that did not show up here.

Since you know how to use functions I put the first for loop in: void InitArray(int a[]). For the most part this leaves "main" to drive the functions, as it should, and not be the program.

The other change I made is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void SortPrint(int a[], int pass)
{
    cout << "pass " << pass + 1 << ": ";

    for (int i = 0; i < MAXSIZE; i++)
    {
        cout << a[i] << " ";
    }

    std::cout << "   Press Enter: ";  // <--- Added.
    std::cin.ignore();

    //cout << endl;  // <--- Uncomment if you like, but I did comment it out for testing.
}

I changed the name of this function to better describe what it is used for. The single letter "p" is OK, but "pass" better describes what it is for.

In line 3 adding 1 to "pass" gives a better display for what people are use to. Not everyone is use to starting at zero.

The "Print" function referred to on line 12 of the first code is basically your original "BubbleSort" function, changed to "print", and minus the second parameter and the first line leaving just the for loop to print the array. Inside the for loop you have the choice of:
1
2
//cout << a[i] << " ";
cout << std::setw(4) << a[i];  // <--- "setw()" requires "<iomanip>". 

The 4 not only gives you room for 3 digits, but an extra space for spacing out the line. Use whichever one you like.

The output I ended up with is:


             Unsorted array
----------------------------------------
  93  13  94  74  93  48  24  41   4  80

pass 1: 4 93 94 74 93 48 24 41 13 80    Press Enter:
pass 2: 4 13 94 93 93 74 48 41 24 80    Press Enter:
pass 3: 4 13 24 94 93 93 74 48 41 80    Press Enter:
pass 4: 4 13 24 41 94 93 93 74 48 80    Press Enter:
pass 5: 4 13 24 41 48 94 93 93 74 80    Press Enter:
pass 6: 4 13 24 41 48 74 94 93 93 80    Press Enter:
pass 7: 4 13 24 41 48 74 80 94 93 93    Press Enter:
pass 8: 4 13 24 41 48 74 80 93 94 93    Press Enter:
pass 9: 4 13 24 41 48 74 80 93 93 94    Press Enter:

             Sorted array
----------------------------------------
   4  13  24  41  48  74  80  93  93  94



I think this is what you are looking for. If not let me know.

I meant to mention this earlier. Anytime you have a "std::cin >>" or in this case the use of "std::cin.ignore()" it is best to give a prompt to let the user know what to do, i.e., what the program is waiting for.

Andy
Topic archived. No new replies allowed.