I wrote this trying to understand templates, functors and inheritance. it works but I want to know if there's a better way. Is a base and derived class overkill for a sorting function? How cand I make it better?
/*
sorting test
Class based sorting
by Kimberly Hamrick
*/
#include <algorithm> // for C+'s sort
#include <iostream> // for C++ I/O
#include <stdlib.h> // for random numbers
using namespace std;
namespace hamrick {
template <typename T>
class sort_base {
public:
virtual void operator()( T array[], const int size ) const = 0;
};
template <typename T>
class bubble_sort: public sort_base<T> {
public:
virtual void operator()( T array[], const int size ) const;
private:
// save the array for bubble_up
mutable T *_array;
// bubble up each element of the array
void bubble_up( int from, const int downto ) const;
};
template <typename T>
void bubble_sort<T>::operator()( T array[], const int size ) const {
// save the array
_array = array;
// bubble up each element of the array
for ( int x = 0; x < size; ++x )
bubble_up( size - 1, x );
}
template <typename T>
void bubble_sort<T>::bubble_up( int from, const int downto ) const {
// bubble up to the last sorted element
while ( from > downto ) {
if ( _array[from] < _array[from - 1] )
swap( _array[from], _array[from - 1] );
--from;
}
}
}
// Check that an array of T is sorted
template <typename T>
bool issorted( T array[], const int size ) {
bool sorted = true;
// it's sorted if the previous element is smaller
// than the current element for all elements
for ( int i = 1; i < size; i++ ) {
if ( array[i - 1] > array[i] ) {
sorted = false;
break;
}
}
return sorted;
}
template <int size>
void unit_test( const hamrick::sort_base<int>& sorter ) {
int array[size];
int copy[size];
// create a random array
for ( int i = 0; i < size; ++i )
copy[i] = array[i] = rand();
// make sure it's sorted
cout<<"before sort -- "<< boolalpha << issorted( array, size ) <<endl;
sorter( array, size );
cout<<"after sort -- "<< boolalpha << issorted( array, size ) <<endl<<endl;
// make sure it's sorted the right way
sort( copy, copy + size );
for ( int i = 0; i < size; ++i ) {
if ( array[i] != copy[i] ) {
cout<<"bad sort!"<<endl;
break;
}
}
}
int main() {
const int size = 10;
unit_test<size>( hamrick::bubble_sort<int>() );
return 0;
}