Pagini recente » Cod sursa (job #1190240) | Cod sursa (job #2365345) | Cod sursa (job #2816513) | Cod sursa (job #3003250) | Cod sursa (job #1190370)
//heapsort
#include <stdio.h>
#define N_MAX 500000
int heap[ N_MAX ], dr = 0;
inline void del(){
int aux, gasit = 1, poz = 0, a, b, poz2;
aux = heap[ dr - 1 ]; heap[ dr - 1 ] = heap[ 0 ]; heap[ 0 ] = aux;
dr--;
while ( poz * 2 + 1 < dr && gasit ){
gasit = 0;
poz2 = poz;
a = poz * 2 + 1;
b = poz * 2 + 2;
if ( heap[ a ] > heap[ poz ] ){
poz2 = a;
gasit = 1;
}
if ( b < dr ){
if ( heap[ b ] > heap[ poz2 ] ){
poz2 = b;
gasit = 1;
}
}
aux = heap[ poz ]; heap[ poz ] = heap[ poz2 ]; heap[ poz2 ] = aux;
poz = poz2;
}
return ;
}
inline void add ( int x ){
int poz = dr;
while ( poz != 0 && heap[ ( poz - 1 ) / 2 ] < x){
heap[ poz ] = heap[ ( poz - 1 ) / 2 ];
poz = ( poz - 1 ) / 2;
}
heap[ poz ] = x;
dr++;
return ;
}
int main()
{
FILE *in = fopen ( "algsort.in", "r" );
int n;
fscanf ( in, "%d", &n );
int i, x;
for ( i = 0; i < n; i++ ){
fscanf ( in, "%d", &x );
add ( x );
}
fclose ( in );
for ( i = 0; i < n - 1; i++ ){
del();
}
FILE *out = fopen ( "algsort.out", "w" );
for ( i = 0; i < n; i++ ){
fprintf ( out, "%d ", heap[ i ] );
}
fclose ( out );
return 0;
}