Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) BubbleSort

 

BubbleSort is a sorting code snippet to perform a bubble sort. Prefer to use the STL algorithm std::sort.

 

#include <vector>
#include <algorithm>

//From http://www.richelbilderbeek.nl/CppBubbleSort.htm
template <class T>
void BubbleSort(std::vector<T>& v)
{
  const int size = v.size();
  for(int i=0; i!=size-1; ++i)
  {
    for(int j=0; j!=size-i-1; ++j)
    {
      if(v[j] > v[j+1])
      {
        std::swap(v[j],v[j+1]);
      }
    }
  }
}

 

 

 

 

 

BubbleSort test

 

The code below tests BubbleSort by checking if it yields the same results as std::sort.

 

#include <vector>
#include <algorithm>

//From http://www.richelbilderbeek.nl/CppBubbleSort.htm
template <class T>
void BubbleSort(std::vector<T>& v)
{
  const int size = v.size();
  for(int i=0; i!=size-1; ++i)
  {
    for(int j=0; j!=size-i-1; ++j)
    {
      if(v[j] > v[j+1])
      {
        std::swap(v[j],v[j+1]);
      }
    }
  }
}

#include <cassert>

//From http://www.richelbilderbeek.nl/CppBubbleSort.htm
int main()
{
  //Create a std::vector<int> with random values
  std::vector<int> v;
  for(int i=0; i!=100; ++i) v.push_back(std::rand() % 1000);
  //Create a copy of this std::vector
  std::vector<int> v1(v);
  //Sort v using std::sort
  std::sort(v.begin(),v.end());
  //Sort v1 using BubbleSort
  BubbleSort(v1);
  //Assert they are equal
  assert(v1==v);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict