This is an effort to implement insertion sort in C++ way using Standard Template Library. The below implementation is for vector of any type. Two STL libraries algorithm has been used.
1. std::lower_bound
2. std::rotate
The implementation cross compiler compatible, tested on GNU C++ (5.4.0) and Microsoft C++ (2010).
//g++ 5.4.0
#include < iostream >
#include < algorithm >
#include < vector >
template< typename T >
void insertionSort(std::vector< T > &vec)
{
typedef typename std::vector< T >::value_type vt;
typename std::vector< vt >::iterator itBegin = vec.begin();
typename std::vector< vt >::iterator itEnd = vec.end();
for(typename std::vector< vt >::iterator it = itBegin; it != itEnd; ++it)
{
typename std::vector::iterator ins = std::lower_bound(itBegin, it, *it);
std::rotate(ins, it, std::next(it));
}
}
int main()
{
int arr[] = {34, 20, 99, 10, 23};
std::vector< int > v(std::begin(arr), std::end(arr));
// Before sorting
for (std::vector< int >::const_iterator i = v.begin(); i != v.end(); ++i)
{
std::cout << *i << ' ';
}
std::cout << std::endl;
insertionSort(v);
// After sorting
for (std::vector< int >::const_iterator iSort = v.begin(); iSort != v.end(); ++iSort)
{
std::cout << *iSort << ' ';
}
std::cout << std::endl;
}
1. std::lower_bound
2. std::rotate
The implementation cross compiler compatible, tested on GNU C++ (5.4.0) and Microsoft C++ (2010).
//g++ 5.4.0
#include < iostream >
#include < algorithm >
#include < vector >
template< typename T >
void insertionSort(std::vector< T > &vec)
{
typedef typename std::vector< T >::value_type vt;
typename std::vector< vt >::iterator itBegin = vec.begin();
typename std::vector< vt >::iterator itEnd = vec.end();
for(typename std::vector< vt >::iterator it = itBegin; it != itEnd; ++it)
{
typename std::vector
std::rotate(ins, it, std::next(it));
}
}
int main()
{
int arr[] = {34, 20, 99, 10, 23};
std::vector< int > v(std::begin(arr), std::end(arr));
// Before sorting
for (std::vector< int >::const_iterator i = v.begin(); i != v.end(); ++i)
{
std::cout << *i << ' ';
}
std::cout << std::endl;
insertionSort(v);
// After sorting
for (std::vector< int >::const_iterator iSort = v.begin(); iSort != v.end(); ++iSort)
{
std::cout << *iSort << ' ';
}
std::cout << std::endl;
}
Comments