Pagini recente » Cod sursa (job #2788068) | Cod sursa (job #2897979)
#include <vector>
#include <fstream>
#include <iterator>
/*
*
*/
using namespace std;
vector<int> v;
int size_threshold;
inline void swap( int x, int y )
{
v[x]+=v[y];
v[y]=v[x]-v[y];
v[x]-=v[y];
}
void siftdown( int s, int e )
{
int w=2*s+1;
while( w < e )
{
if( w+1 < e && v[w+1] > v[w] )
++w;
if( v[w] <= v[s] )
return;
swap( s, w );
s=w;
w=2*s+1;
}
}
void downheap( int s, int e )
{int r=2*s+1;
while( r < e )
{
if( r+1 < e && v[r] < v[r+1] ) ++r;
if( v[r] <= v[s] ) return; //has heap structure
swap( r, s );
s=r;
r=2*s+1;
}
}
void HeapSort( int s, int e )
{
for( int w=e/2-1; w > s; --w )
downheap( w, e ); //creat a heap from the arrat v
downheap( s, e );
for( e=e-1; e > s; --e )
{
swap( s, e );
downheap( s, e );
}
}
int main()
{int n;
ifstream in("algsort.in");
in>>n;
copy( istream_iterator<int>(in), istream_iterator<int>(), back_inserter(v) );
ofstream out("algsort.out");
HeapSort( 0, n );
copy( v.begin(), v.end(), ostream_iterator<int>(out, " " ) );
return 0;
}