Cod sursa(job #2452926)

Utilizator Tudor06MusatTudor Tudor06 Data 1 septembrie 2019 19:14:50
Problema Sortare prin comparare Scor 20
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <stdio.h>
#include <stdlib.h>
#define MAXN 1000

int heap[MAXN];

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;
}