Everyone should know the bubble sort method of organising an array. I sat down and made some improvements as I can imagine how bad this method of sorting an array is with really large arrays. What do you guys think?
Code:
// Enhanced bubble sort
#include <cstdlib>
using std::rand;
using std::srand;
#include <iostream>
using std::cout;
using std::cin;
// Prototypes
void bubblesort( int array[], int );
int main()
{
const int arraySize = 100;
int array[ arraySize ];
srand( time( 0 ) );
// Simply enters random values into the array
for( int i = 0; i < arraySize; i++)
array[ i ] = ( 1 + rand() % 1000 );
cout << "Unsorted Array: \n";
// Outputs all elements of the array before being sorted
for( int i = 0; i < arraySize; i++ )
cout << array[ i ] << ' ';
bubblesort( array, arraySize );
cout << "\n\nSorted Array: \n";
// Outputs all elements of the array after being sorted
for( int i = 0; i < arraySize; i++ )
cout << array[ i ] << ' ';
cout << "\n\nPress a key to quit . . . ";
cin.get();
return 0;
}
void bubblesort( int array[], int size )
{
int hold; // to temporarily hold the variable while sorting
int reduce = 0; // speeds up the bubble sort by removing comparrisons not needed
int swaps = 0; // counts how many swaps have been made during execution
// To control number of passes
for( int pass = 1; pass < size; pass++, reduce++ )
{
// Controls number of comparrisons per pass
for( int j = 0; j < size - 1 - reduce; j++ )
if( array[ j ] > array[ j + 1 ] )
{
hold = array[ j ];
array[ j ] = array[ j + 1 ];
array[ j + 1 ] = hold;
swaps++;
}
// If no swaps have been made then the data must already be in the correct
// order, so the sorting should terminate
if( swaps == 0 )
pass = size;
}
}