1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
//--------------------------------------------------------------------------
// bubble_sort
//--------------------------------------------------------------------------
template <typename Iterator, typename Predicate>
bool iter_swap_if( Iterator a, Iterator b, Predicate& f )
{
bool result = f( *a, *b );
if (result) std::iter_swap( a, b );
return result;
}
template <typename Iterator, typename Compare>
void bubble_sort( Iterator begin, Iterator end, Compare compare )
{
bool any = true;
while (any and (begin != end--))
{
any = false;
for (Iterator i = begin; i != end; ++i)
any |= iter_swap_if( i + 1, i, compare );
}
}
template <typename Iterator>
void bubble_sort( Iterator begin, Iterator end )
{
bubble_sort( begin, end,
std::less <typename std::iterator_traits <Iterator> ::value_type> () );
}
//--------------------------------------------------------------------------
// bidirectional_bubble_sort
//--------------------------------------------------------------------------
template <typename Iterator, typename Compare>
void bidirectional_bubble_sort( Iterator begin, Iterator end, Compare compare )
{
bool any = true;
while (any)
{
any = false;
if (begin != end--)
{
for (Iterator i = begin; i != end; ++i)
any |= iter_swap_if( i + 1, i, compare );
}
if (any and (begin++ != end))
{
for (Iterator i = end; i-- != begin; )
any |= iter_swap_if( i, i - 1, compare );
}
}
}
template <typename Iterator>
void bidirectional_bubble_sort( Iterator begin, Iterator end )
{
bidirectional_bubble_sort( begin, end,
std::less <typename std::iterator_traits <Iterator> ::value_type> () );
}
|