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
|
#include <iostream>
#include <stack>
#include <functional>
template < typename T, typename C, typename CMP = std::less<> >
void bubble_sort( std::stack<T,C>& stk, CMP cmp = {} )
{
std::stack<T,C> result ;
while( !stk.empty() )
{
// extract the value at the top of stk
T curr_val = std::move( stk.top() ) ;
stk.pop() ;
// bubble it to the right position at the top of the result
// the sorted order depends on the binary predicate used for comparing elements
while( !result.empty() && cmp( result.top(), curr_val ) )
{
stk.push( std::move( result.top() ) ) ;
result.pop() ;
}
result.push( std::move(curr_val) ) ;
}
// now result contains the items in sorted order and original stack is empty.
// swap the two, to move the sorted items to the original stack
using std::swap ;
swap( result, stk ) ;
}
template < typename T, typename C >
void print( std::stack<T,C> stk ) // destructive
{
while( !stk.empty() )
{
std::cout << stk.top() << ' ' ;
stk.pop() ;
}
std::cout << '\n' ;
}
int main()
{
std::stack<int> stk ;
for( int v : { 23, 11, 56, 42, 78, 18, 34, 86, 17 } ) stk.push(v) ;
print(stk) ;
bubble_sort(stk) ; // compare using <
print(stk) ;
bubble_sort( stk, std::greater<>{} ) ; // compare using >
print(stk) ;
}
|