Cod sursa(job #371879)

Utilizator titusuTitus C titusu Data 7 decembrie 2009 17:37:01
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
using namespace std;
#include <fstream>
#include <iostream>
#define MAX 500005

int v[MAX], H[MAX], n, nH;

void read(){
  ifstream fin("algsort.in");
  fin>>n;
  for(int i=1;i<=n;i++)
    fin>>v[i];
}
ofstream fout("algsort.out");
void write(){
  
  for(int i=n; i ; --i)
    fout<<v[H[i]]<<" ";
  fout<<endl;
  /*for(int i=n; i ; --i)
    cout<<H[i]<<" ";
  cout<<endl;
  */
    
}

void Promoveaza(int k){
  int esteHeap = 0, aux;
  while(k/2 && !esteHeap)
    if(v[H[k/2]] <= v[H[k]])
      esteHeap=1;
    else{
      aux = H[k/2]; H[k/2] = H[k]; H[k] = aux;
      k /= 2;
    }
}

void Cerne(int k){
  int esteHeap = 0, i ,aux;
  while(!esteHeap && 2*k<=nH){
    i= 2*k;
    if(i+1 <=nH && v[H[i]]>=v[H[i+1]])
      i++;
    if(v[H[k]]<=v[H[i]])
      esteHeap = 1;
    else{
      aux = H[i] ; H[i] = H[k] ; H[k] =aux;
      k=i;
      }
  }
}

void hs(){
  nH=0;
  for(int i=1;i<=n;i++){
    H[i] = i;
    Promoveaza(i);
  }
  nH = n;
  for( ; nH > 1 ; ){
    int aux=H[1]; H[1] = H[nH]; H[nH] = aux;
    nH--;
    Cerne(1);
  }
}

int main(){
  read();
  hs();
  write();
  return 0;
}