I created a program that performs a bubble sort in ascending order to 10 integers. It prints what happens after each pass and shows which values at the end of the list is already in its proper position.
Here's my code which I patterned from the algorithm given in my book.
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 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
using namespace std;
int myArray[10];
class BubbleSort {
public:
void sortMe() {
int numCompares = 9;
int last, temp = 0, ctr = 0;
while ( numCompares != 0 ) {
last = 1;
for ( int i = 0; i <= numCompares; i++ ) {
if ( myArray[i] > myArray[ i + 1 ] ) {
temp = myArray[ i ];
myArray[ i ] = myArray[ i + 1 ];
myArray[ i + 1 ] = temp;
last = i;
}
}
numCompares = last - 1;
ctr++;
printPass( ctr, numCompares + 1 );
}
}
void printPass( int c, int nc ) {
int j;
cout << endl << "Pass No. " << c << endl << "\t";
for ( j = 0; j < 10; j++ ) {
if ( j == nc ) {
cout << " | ";
}
cout << "[" << myArray[ j ] << "]";
}
cout << endl;
}
};
int main() {
BubbleSort Bubble;
cout << "Enter 10 integers: ";
for ( int i = 0; i < 10; i++ )
cin >> myArray[ i ];
Bubble.sortMe();
return 0;
}
|
Here's a sample input.
Enter 10 integers: 10 9 8 7 6 5 4 3 2 1
|
And here's the corresponding results for that intput.
Pass No. 1
[9][8][7][6][5][4][3][2][1] | [0]
Pass No. 2
[8][7][6][5][4][3][2][1] | [0][9]
Pass No. 3
[7][6][5][4][3][2][1] | [0][8][9]
Pass No. 4
[6][5][4][3][2][1] | [0][7][8][9]
Pass No. 5
[5][4][3][2][1] | [0][6][7][8][9]
Pass No. 6
[4][3][2][1] | [0][5][6][7][8][9]
Pass No. 7
[3][2][1] | [0][4][5][6][7][8][9]
Pass No. 8
[2][1] | [0][3][4][5][6][7][8][9]
Pass No. 9
[1] | [0][2][3][4][5][6][7][8][9]
|
The ideal result here is that the number 10 must be found at the end of the list at the 1st pass until the last pass since it's the largest value in the list. The sorted values iare separated by the '|' and it increases at each pass.
The problem with my output is that, it does sort the number 10 and put it at the end of the list after the 1st pass. BUT the number it prints is '0' instead of '10'. Thus, at the 2nd pass, the value which is supposed to be 10 is still being moved to the front of the list. (e.g. at the 2nd pass, 9 is greater than 0, which is supposed to be 10, so 9 is found at the end, instead of 10).
How will I fix this issue? Which part of the code needs some tweaking? Thanks a lot.