C++ Bubble Sort

A simple implementation of Bubble Sort algorithm:

Also on Blogger

– Random Generator:

template <typename Comparable>
void fillRandom(vector<Comparable> &iArray)
{
	srand((unsigned)time(0));
	for(vector<Comparable>::size_type i = 0; i < iArray.size(); i++)
	{
		iArray[i] = rand();
	}
}

– Bubble Sort Algorithm:

template <typename Comparable>
void bubbleSort(vector<Comparable> &a)
{
	bool sorted = false;
	for(int pass = 1; pass < a.size() && !sorted; pass++)
	{
		sorted = true; // Optimize and stop if array is already sorted
		for(int index = 0; index < a.size() - pass; index++)
		{
			if(a[index] > a[index + 1])
			{
				swap(a[index], a[index + 1]);
				sorted = false;
			}
		}
	}
}

– Bubble Sort Algorithm, inverted version:

template <typename Comparable>
void bubbleSortInverted(vector<Comparable> &a)
{
	bool sorted = false;
	for(int pass = a.size() - 1; pass > 0 && !sorted; pass--)
	{
		sorted = true; // Optimize and stop if array is already sorted
		for(int index = a.size() - 1; index > 0; index--)
		{
			if(a[index] < a[index - 1])
			{
				swap(a[index], a[index - 1]);
				sorted = false;
			}
		}
	}
}
Advertisements

Tagged: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: