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