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 63 64 65 66
|
#include <iostream>
template < typename T > void sort( T a[], int n, int& num_cmp, int& num_swap )
{
num_cmp = num_swap = 0 ;
for( int i = 0 ; i < n ; ++i )
{
for( int j = i+1 ; j < n ; ++j )
{
++num_cmp ;
if( a[j] < a[i] )
{
++num_swap ;
const T temp = a[i] ;
a[i] = a[j] ;
a[j] = temp ;
}
}
}
}
template < typename T > void print( const T a[], int n )
{
std::cout << "[ " ;
for( int i = 0 ; i < n ; ++i ) std::cout << a[i] << ' ' ;
std::cout << "] (size:" << n << ")" ;
}
template < int SZ > void test()
{
int num_cmp = 0 ;
int num_swap = 0 ;
int seq[SZ] = {} ; // all zeroes
std::cout << "[ ... ] (size:" << SZ << ")" ;
sort( seq, SZ, num_cmp, num_swap ) ;
std::cout << " #compares: " << num_cmp << '\n' ;
}
int main()
{
const int n = 10 ;
int num_cmp = 0 ;
int num_swap = 0 ;
int a[n] = { 7, 10, 23, 32, 45, 56, 62, 75, 83, 94 } ;
print( a, n ) ;
sort( a, n, num_cmp, num_swap ) ;
std::cout << " #compares: " << num_cmp << " #swaps: " << num_swap << "\n\n" ;
int b[n] = { 90, 81, 72, 63, 54, 45, 36, 27, 18, 9 } ;
print( b, n ) ;
sort( b, n, num_cmp, num_swap ) ;
std::cout << " #compares: " << num_cmp << " #swaps: " << num_swap << "\n\n" ;
int c[n] = { 81, 18, 9, 72, 36, 54, 45, 90, 27, 63 } ;
print( c, n ) ;
sort( c, n, num_cmp, num_swap ) ;
std::cout << " #compares: " << num_cmp << " #swaps: " << num_swap << "\n\n" ;
test<50>() ;
test<250>() ;
test<1000>() ;
test<30'000>() ;
}
|