I'm trying to do a bubble sort on an array containing 4 indexes of integers. However, it is working, but after the first run through, I want it to stop checking the last index (because it's already set properly), then after the second run through, it needs to not check the last TWO indexes, and so on... Any advice would be appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int theData[ ] = {45, 12, 23, 34};
constint SIZE = 4;
int main ( )
{
// sort the array in ascending order
// print out messages to see what is happening
for (int j = 0; j < SIZE-1; j++) // index for outer loop is j
{
cout << "\n\nIteration " << j << " for the outer loop.";
for (int i = 0; i < SIZE-1; i++) // index for inner loop is i
{
cout << "\n\nIteration " << i << " for the inner loop.";
if (theData[ i ] > theData[ i + 1] )
swap( theData[ i ], theData[ i + 1] );
}
}
Since j is equal to 1 less than the number of elements already sorted, consider modifying the terminating condition of the inner for loop to somehow use j also.
He's saying that if you decrement your SIZE variable when you finish one iteration of the loop, you can stop earlier next time. However, you don't want to do that with your actual size variable, so you should create a temporary variable and set it equal to size.
int theData[ ] = {45, 12, 23, 34};
constint SIZE = 4;
int size = 5;
int main ( )
{
// sort the array in ascending order
// print out messages to see what is happening
for (int j = 0; j < SIZE-1; j++) // index for outer loop is j
{
//cout << "\n\nIteration " << j << " for the outer loop.";
for (int i = 0; i < size; i++) // index for inner loop is i
{
cout << "\n\nIteration " << i << " for the inner loop.";
if (theData[ i ] > theData[ i + 1] )
swap( theData[ i ], theData[ i + 1] );
size--;
}
}
Nevermind, I got it... I did it differently though.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for (int j = 0; j < SIZE-1; j++) // index for outer loop is j
{
bool changed = false;
cout << "\n\nIteration " << j << " for the outer loop.";
for (int i = 0; i < (SIZE-1-j); i++) // index for inner loop is i
{
cout << "\n\nIteration " << i << " for the inner loop.";
if (theData[ i ] > theData[ i + 1] )
{
swap( theData[ i ], theData[ i + 1] );
changed = true;
}
}
if (changed)
break;
}