Created
March 9, 2014 06:40
-
-
Save hobelinm/9443743 to your computer and use it in GitHub Desktop.
Simple implementation about Selection Sort in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <ctime> | |
// A random number generator | |
void fillRandom(vector<int> &iArray) | |
{ | |
srand((unsigned)time(0)); | |
for(int i = 0; i < iArray.size(); i++) | |
{ | |
iArray[i] = rand(); | |
} | |
} | |
// Selection sort 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 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment