Pagini recente » Cod sursa (job #502072) | Cod sursa (job #2917748) | Cod sursa (job #509366) | Cod sursa (job #614938) | Cod sursa (job #1336240)
#include<fstream>
using namespace std;
ifstream fin( "algsort.in" );
ofstream fout( "algsort.out" );
const int nmax = 500000;
int hn, h[ 2 * nmax + 2 ];
void heap_swap( int a, int b ) {
int aux = h[ a ]; h[ a ] = h[ b ]; h[ b ] = aux;
}
void urcare( int pos ) {
while ( pos > 1 && h[ pos / 2 ] > h[ pos ] ) {
heap_swap( pos / 2, pos );
pos /= 2;
}
}
void coborare( int pos ) {
bool ok = 1;
int shp;
while ( ok == 1 && 2 * pos <= hn ) {
shp = 2 * pos;
if ( 2 * pos + 1 <= hn && h[ 2 * pos + 1 ] < h[ 2 * pos ] ) {
++ shp;
}
if ( h[ shp ] < h[ pos ] ) {
heap_swap( pos, shp );
pos = shp;
} else {
ok = 0;
}
}
}
void heap_insert( int x ) {
h[ ++ hn ] = x;
urcare( hn );
}
void heap_erase() {
heap_swap( 1, hn );
-- hn;
coborare( 1 );
}
int main() {
int n, x;
fin >> n;
hn = 0;
for( int i = 0; i < n; ++ i ) {
fin >> x;
heap_insert( x );
}
for( int i = 0; i < n; ++ i ) {
fout << h[ 1 ] << " ";
heap_erase();
}
fout << "\n";
fin.close();
fout.close();
return 0;
}