Pagini recente » Cod sursa (job #1070953) | Cod sursa (job #1343146) | Cod sursa (job #1108375) | Cod sursa (job #512261) | Cod sursa (job #353502)
Cod sursa(job #353502)
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define InFile "algsort.in"
#define OutFile "algsort.out"
/*
*
*/
using namespace std;
ifstream in;
ofstream out;
unsigned *v;
inline void swap( unsigned a, unsigned b )
{unsigned aux=v[a];
v[a]=v[b];
v[b]=aux;
}
void downheap( unsigned begin, unsigned end )
{
for( unsigned root=2*begin+1; root < end; )
{
if( root+1 < end && v[root] < v[root+1] ) ++root;
if( v[root] <= v[begin] ) return;
swap( root, begin );
begin=root;
root=2*begin+1;
}
}
void HeapSort( unsigned begin, unsigned end )
{
for( unsigned w=end/2-1; w > 0; --w )
downheap( w, end );
downheap( 0, end );
for( --end; end > 0; --end )
{
swap( begin, end );
downheap( begin, end );
}
swap( begin, end );
downheap( begin, end );
}
int main()
{unsigned N,i;
in.open( InFile );
in>>N;
v=(unsigned*)malloc( N*sizeof( unsigned ) );
for( i=0; i < N; ++i ) in>>v[i];
out.open( OutFile );
HeapSort( 0, N );
copy( v, v+N, ostream_iterator< unsigned >( out, " " ) );
return EXIT_SUCCESS;
}