im just doing a little exercise on the bubble sort algorithim, i included two ways of incresing its speed.
1. Breaking out of the loop if no swaps are made
2. Decreasing the inner loops lenght each pass
I think there is two ways of doing it. This way i think is better coding practise but it takes alot longer to compile. is it confusing the compiler a bit?

``````const int SIZE = 10;//size of array
const int UPPER = 10;//highest value

int main()
{
int array[ SIZE ];
int temp;

srand( time( 0 ) );

for ( int counter = 0; counter <= SIZE; counter++ )
{
array[ counter ] = rand() % UPPER;
}//end for

for ( int pass = 0; pass < SIZE ; pass++ )
{
int swap = 0;
for ( int counter = 0; counter < ( SIZE - pass ); counter++ )
{

if ( array[ counter ] > array[ counter + 1 ] )
{
temp = array[ counter ];
array[ counter ] = array[ counter + 1 ];
array[ counter + 1 ] = temp;
swap++;
}//end if
}//end inner for
if ( swap == 0 )// no swaps made
{
break;
}
}//end outer for

for ( int counter = 0; counter <= SIZE; counter++ )
{
cout<< array[ counter ]<< "\n";
}//end for
return 0;
}``````

the other way i had it was

``````for ( int pass = 0; pass < SIZE ; pass++ )
{
int swap = 0;
int i = 0;
for ( int counter = 0; counter < ( SIZE - i ); counter++ )
{

if ( array[ counter ] > array[ counter + 1 ] )
{
temp = array[ counter ];
array[ counter ] = array[ counter + 1 ];
array[ counter + 1 ] = temp;
swap++;
}//end if
}//end inner for
i++;
if ( swap == 0 )// no swaps made
{
break;
}
}//end outer for``````

which way is better

## All 4 Replies

confusing the compiler? reducing cases will always simplify runtime.

You have a problem understanding loops and arrays. You have

``````const int SIZE = 10;//size of array
...
int array[ SIZE ];``````

Then your loop is defined as

``for ( int counter = 0; counter <= SIZE; counter++ )``

Array size is 10, you load 11 values and blow past your array. You have to make sure you never reference array or beyond.

As for your question, the first one. In the second code, all i represents is pass so it's a waste of space.

You have a problem understanding loops and arrays. You have

``````const int SIZE = 10;//size of array
...
int array[ SIZE ];``````

Then your loop is defined as

``for ( int counter = 0; counter <= SIZE; counter++ )``

Array size is 10, you load 11 values and blow past your array. You have to make sure you never reference array or beyond.
.

is this better?

``for ( int counter = 0; counter < SIZE; counter++ )``

im noob so i always have to think about whether to put < or <=

my mistake ty

is this better?

``for ( int counter = 0; counter < SIZE; counter++ )``

Yes. Now you have more loops. Check them, too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.