Okay, so I just created a bubble sort to sort 50 random numbers in an array. I've been able to get it down to 1134 comparisons so far. I'm pretty sure that's the least number possible, but does anyone know if I can get it reduced even lower? I want it to organize these numbers with the least amount of comparisons possible. Here's my code:
#include <iostream>
#include <cstdlib>
usingnamespace std;
constint SIZE = 50;
int globalCount = 0;
bool compare(int, int);
void swap(int&, int&);
int main( )
{
// declare and initialize a large array
int data[SIZE];
srand(0); // seed the random number generator
for (int i = 0; i < SIZE; i++)
{
data[ i ] = rand( );
}
cout << "\nPrint out the unsorted array:";
for (int i = 0; i < SIZE; i++)
{
cout << "\ndata[ " << i << " ] = " << data[ i ];
}
cout << endl;
//Bubble Sort Starts!
int j = 0;
bool again = true;
while ((j<SIZE-1 && again == true))
{
int count = 0;
again = false;
for (int i = 0; i < SIZE-1-j; i++) // index for inner loop is i
{
if (compare(data[i],data[i+1]) == true)
{
swap( data[ i ], data[ i + 1] );
count++;
}
}
if (count > 0)
again = true;
j++;
}
// print out the sorted array and the value of globalCount
for (int i = 0; i < SIZE; i++)
{
cout << "\ndata[ " << i << " ] = " << data[ i ];
}
cout << "\n\n";
cout << globalCount << " Comparison's were done to sort the array.\n";
system("PAUSE");
return 0;
}
Compare() function - Used to compare and keep track of the number of compares.
1 2 3 4 5 6 7 8 9
bool compare(int n1, int n2)
{
globalCount++;
if ( n1 > n2)
returntrue;
elsereturnfalse;
}
I think you're accessing past the end of the array:
When j==0, i==[0..n-1-j]==[0..n-1].
Later on, you're comparing data[i] and data[i+1]; OR, data[n-1] and data[n-1+1]
I doubt you can get many less comparisons than (n^2-n)/2 without the array being partially sorted at the start. If you need more speed, change algorithms. Insertion sort has good times.