Pagini recente » Cod sursa (job #597729) | Cod sursa (job #2667439) | Cod sursa (job #2679941) | Cod sursa (job #2345039) | Cod sursa (job #2452927)
#include <stdio.h>
#include <stdlib.h>
#define MAXN 1000
int heap[500000];
int max( int a, int b ) {
if ( a > b )
return a;
return b;
}
void insert_heap( int x, int n ) {
int aux;
heap[n] = x;
n ++;
int i = n - 1;
while ( i > 0 && heap[i] > heap[( i - 1 ) / 2] ) {
aux = heap[i];
heap[i] = heap[( i - 1 ) / 2];
heap[( i - 1 ) / 2] = aux;
i = ( i - 1 ) / 2;
}
}
void remove_heap( int i, int n ) {
int aux = heap[i];
heap[i] = heap[n - 1];
heap[n - 1] = aux;
n --;
while ( i * 2 + 2 < n && heap[i] < max( heap[i * 2 + 1], heap[i * 2 + 2] ) ) {
aux = heap[i];
if ( max( heap[i * 2 + 1], heap[i * 2 + 2] ) == heap[i * 2 + 1] ) {
heap[i] = heap[i * 2 + 1];
heap[i * 2 + 1] = aux;
i = i * 2 + 1;
} else {
heap[i] = heap[i * 2 + 2];
heap[i * 2 + 2] = aux;
i = i * 2 + 2;
}
}
}
int main() {
FILE *fin = fopen( "algsort.in", "r" ), *fout = fopen( "algsort.out", "w" );
int i, a, n;
fscanf( fin, "%d", &n );
for ( i = 0; i < n; i ++ ) {
fscanf( fin, "%d", &a );
insert_heap( a, i );
}
for ( i = n; i > 0; i -- ) {
remove_heap( 0, i );
}
for ( int j = 0; j < n; j ++ )
fprintf( fout, "%d ", heap[j] );
fprintf( fout, "\n" );
fclose( fout );
fclose( fin );
return 0;
}