C++ Selection Sort

A brief implementation about Selection Sort:

– First we need a random generator:

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

– Selection Sort algorithm starting from biggest to smallest:

template <typename Comparable>
void selectionSort(vector<Comparable> &a, int last)
{
	if(last <= 0)
	{
		return;
	}

	vector<Comparable>::size_type largest = a[0];
	int index = 0;
	for(int i = 1; i <= last; i++)
	{
		if(a[i] > largest)
		{
			largest = a[i];
			index = i;
		}
	}

	vector<Comparable>::size_type buffer = a[index];
	a[index] = a[last];
	a[last] = buffer;
	selectionSort(a, last - 1);
}

– Selection Sort algorithm starting from smallest to biggest:

template <typename Comparable>
void selectionSortInvert(vector<Comparable> &a, int first)
{
	if(first >= a.size())
	{
		return;
	}

	Comparable smallest = a[first];
	int index = first;
	for(int i = first + 1; i < a.size(); i++)
	{
		if(a[i] < smallest)
		{
			smallest = a[i];
			index = i;
		}
	}

	vector<Comparable>::size_type buffer = a[index];
	a[index] = a[first];
	a[first] = buffer;
	selectionSortInvert(a, first + 1);
}

– Finally, libraries used:

#include <iostream>
#include <vector>
#include <ctime>
Advertisements

One thought on “C++ Selection Sort

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: