Cod sursa(job #353246)

Utilizator alexandru92alexandru alexandru92 Data 4 octombrie 2009 15:09:29
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
/* 
 * File:   main.cpp
 * Author: speedemon
 *
 * Created on October 2, 2009, 7:09 PM
 */
#include <fstream>
#include <cstdlib>
#define InFile "algsort.in"
#define OutFile "algsort.out"
#define temp template< class T >

/*
 * 
 */

using namespace std;
ifstream in;
ofstream out;
temp class HeapSort
{
    T *v;
    unsigned size;
    inline void swap( unsigned, unsigned );
    void downheap( unsigned, unsigned );
public:
    HeapSort();
    ~HeapSort();
    inline unsigned getsize();
    inline void push( istream& );
    inline void output( ostream& );
    void heapsort( unsigned, unsigned );
};
temp HeapSort<T>::HeapSort()
{size=0;
    v=new T;
}
temp HeapSort<T>::~HeapSort()
{
    delete[] v;
}
temp inline unsigned HeapSort<T>::getsize()
{
    return size;
}
temp inline void HeapSort<T>::push( istream& in )
{++size;
    v=(T*)realloc( (void*)v, size*sizeof(T) );
    in>>v[size-1];
}
temp inline void HeapSort<T>::output( ostream& out )
{
    for( unsigned i=0; i < size; ++i ) out<<v[i]<<' ';
}
temp inline void HeapSort<T>::swap( unsigned a, unsigned b )
{
    v[a]+=v[b];
    v[b]=v[a]-v[b];
    v[a]-=v[b];
}
temp void HeapSort<T>::downheap( unsigned start, unsigned end )
{
    for( unsigned root=2*start+1; root < end; )
    {
        if( root+1 < end && v[root] < v[root+1] ) ++root;
        if( v[root] <= v[start] ) return;
        swap( root, start );
        start=root;
        root=2*start+1;
    }
}
temp void HeapSort<T>::heapsort( unsigned start, unsigned end )
{
    for( int w=end/2-1; w >= 0; -- w )
        downheap( w, end ); 
    for( end=end-1; end > start; --end )
    {
        swap( 0, end );
        downheap( 0, end );
    } 
}
int main()
{int N;
    HeapSort< unsigned > a;
    in.open(InFile);
    in>>N;
    while( N-- )
    {
        a.push(in);
    } 
    a.heapsort( 0, a.getsize() );
    out.open(OutFile);
    a.output( out );
    return EXIT_SUCCESS;
}