Created
March 9, 2014 06:33
-
-
Save hobelinm/9443721 to your computer and use it in GitHub Desktop.
Simple implementation of Bubble Sort algorithm
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
// 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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment