I have been working on this program for a project. Everything runs fine but there is something wrong with my bubble sort. I ran and displayed the result of the function but every so often it shows negative numbers, which it should NOT. And also every so often it does not sort properly, meaning it the my bubble sort function is not sorting them in order some what.
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
int const temp = 10000;
void bubbleSort ( int array [ temp ] );
void radixSort ( int * array, int arraySize );
void display ( int btime);
int main ( )
{
int A1;
int array [ temp ];
char a = '\0';
cout << "\nWould You Like To Perform Bubble and Radix Test? (y/n): ";
cin >> a;
while ( a == 'y' || a == 'Y' )
{
srand ( ( unsigned ) time ( 0 ) );
for ( size_t i = 0; i < temp; i++ )
{
A1 = ( rand ( ) % temp ) + 1 ;
array [ i ] = A1;
bubbleSort ( array );
}
}
while ( a == 'n' || a == 'N' )
{
break;
}
return 0;
}
void bubbleSort ( int array [ temp ] )
{
for ( int i = 0; i < temp; i++ )
{
for ( int j = 0; j < temp - 1; j++ )
{
if ( array [ j ] > array [ j + 1 ] )
{
int temp = array [ j ];
array [ j ] = array [ j + 1 ];
array [ j + 1 ] = temp;
//Test: to see if its working properly.
cout << array [ j + 1 ] << endl; //idk if this should be placed here
}
}
}
}
Problems in your code:
while
loop. You don't make any breaking condition in the loop.Solution: Use you own preferred breaking condition. Something like:
bubbleSort
with an uninitialized array in afor
loop (!).Solution:
Put the
bubbleSort
method calling outside offor
loop,Following is the 'proof' of
bubbleSort()
method implementation which actually works perfectly:And the output is:
Cheers!