Created
December 3, 2012 01:24
-
-
Save hobelinm/4192020 to your computer and use it in GitHub Desktop.
Bubble Sort - 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
template<typename Comparable> void bubbleSort(vector<Comparable> &a); | |
template<typename Comparable> void bubbleSortInverted(vector<Comparable> &a); | |
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; | |
} | |
} | |
} | |
} | |
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