This took me longer to write than I am willing to admit, indicating that I should continue practicing and writing these algorithms.
void insertion_sort( std::vector& v )
{
// leave if there is nothing to sort
if ( v.empty() )
{
return;
}
// go left to right along the vector
std::vector::iterator l2r_it;
l2r_it = v.begin();
l2r_it++;
for ( ; l2r_it != v.end(); l2r_it++ )
{
// go right to left along the vector
std::vector::iterator r2l_it = l2r_it ;
while ( r2l_it != v.begin() &&
*r2l_it < *(r2l_it - 1) )
{
int tmp = *r2l_it;
*r2l_it = *(r2l_it - 1);
*(r2l_it - 1 ) = tmp;
r2l_it--;
}
}
}
No comments:
Post a Comment