Skip to content

Instantly share code, notes, and snippets.

@hobelinm
Created December 3, 2012 01:24
Show Gist options
  • Save hobelinm/4192020 to your computer and use it in GitHub Desktop.
Save hobelinm/4192020 to your computer and use it in GitHub Desktop.
Bubble Sort - C++
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