Cod sursa(job #356568)

Utilizator sapiensCernov Vladimir sapiens Data 15 octombrie 2009 11:20:58
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
using namespace std;
int a[500000],i,N,Nh=N;

void upheap (int x) {
     int y=x,z;
     while (y) {
           if (a[y/2]<a[y]) {
              swap (a[y],a[y/2]);
              y/=2;
           } else y=0;
     }
}

void downheap (int x) {
     int y=x,z;
     do {
         z=0;
         if ((2*y)<=Nh) {
            z=2*y;
            if (((2*y+1)<=Nh)&&(a[2*y+1]>a[2*y])) z=2*y+1;
         }
         if (a[z]>a[y]) {
            swap (a[y],a[z]);
            y=z;
         } else z=0;
     } while (z);
}

void makeheap () {
     for (i=Nh/2; i>=1; i--) downheap (i);
}

void heapsort () {
     while (Nh>1) {
           swap (a[1],a[Nh]);
           Nh-=1;
           downheap (1);
     }
}

int main () {
    ifstream in; ofstream out;
    in.open ("algsort.in"); out.open ("algsort.out");
    in>>N; Nh=N;
    for (i=1; i<=N; i++) in>>a[i];
    makeheap ();
    heapsort ();
    for (i=1; i<=N; i++) out<<a[i]<<" ";
    out<<"\n";
    in.close (); out.close ();
    return 0;
}