Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) InsertionSort

 

InsertionSort is a sorting code snippet to perform an insertion sort.

 

 

#include <algorithm>
#include <vector>
///Sort a std::vector using insertion sort
///From http://www.richelbilderbeek.nl/CppInsertionSort.htm
template <typename T>
void InsertionSort(std::vector<T>& v)
{
  const int size = v.size();
  for(int i=1; i!=size; ++i)
  {
    for(int j=0; j<i; ++j)
    {
      if (v[j] > v[i])
      {
        const int temp = v[j];
        v[j] = v[i];
        for(int k=i; k>j; --k) { v[k] = v[k-1]; }
        v[j+1] = temp;
      }
    }
  }
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml