Oct 30, 2012 at 2:35am UTC
Using Bubble Sort to sort my user input integers. I get bubble sort to sort most of the integers in my array but when I get about 6 or 7 elements the sorting degrades. I will be very appreciative if you will take the time to glance at my code (that I have put a lot of time into) and tell me how I can improve this feature.
THANKS!!!
#include <iostream>
#include <cstdlib>
using namespace std;
void create_array(int*&, int);
void rand_Pop(int*, int);
void Bubble(int*, int);
int main()
{
//declare pointer
int* raPtr;
int size;
//call user to input a size for the list of numbers
cout << "Enter the number of values to sort -> ";
cin >> size;
//function to create a dynamic array using the pointer
create_array(raPtr, size);
//function to populate array with random numbers
rand_Pop(raPtr, size);
//function to sort array in numerical order
Bubble(raPtr, size);
delete [] raPtr; //deallocate array
}
void create_array(int* & randarrPtr, int dim)
{
randarrPtr = new int[dim];
}
void rand_Pop(int* randarray, int dim)
{
srand(time(NULL));
cout << "The following values were 'randomly' created: " << endl;
for(int i = 0; i < dim; i++)
{
randarray[i] = (rand()% 10 + 1);
cout << randarray[i] << " ";
}
cout << endl;
}
void Bubble(int* randarray, int dim)
{
bool sorted;
int temp;
cout << "Here are these values sorted: " << endl;
int cycle = 1;
while(cycle < dim - 1)
{
sorted = false;
cycle++;
for (int j = 0; j < (dim - 1 - cycle); j++)
{
if (randarray[j] > randarray[j + 1])
{
temp = randarray[j];
randarray[j] = randarray[j + 1];
randarray[j + 1] = temp;
sorted = true;
}
}
if (sorted == false)
break;
}
for (int count = 0; count < dim; count++)
{
cout << randarray[count] << " ";
}
cout << endl;
}