Cod sursa(job #856153)

Utilizator BalcauIonutFMI-Balcau Ionut BalcauIonut Data 15 ianuarie 2013 23:20:29
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include<iostream>
#include<fstream>
using namespace std;

void swap(int a[],int i,int l){
    int x=a[i];
    a[i]=a[l];
    a[l]=x;
}

void makeHeap(int a[],int i,int n){
    int max=i,x;
    x=i<<1;
    if(x<=n && a[max]<a[x])
        max=x;
    x+=1;
    if(x<=n && a[max]<a[x])
        max=x;
    if(max!=i){
        swap(a,i,max);
        makeHeap(a,max,n);
    }
}

void buildHeap(int a[],int &n){
    for(int i=n/2;i>0;--i)
        makeHeap(a,i,n);
}


void heapSort(int a[],int &n){
    buildHeap(a,n);
    int l=n;
    while(l>1){
        swap(a,1,l);
        makeHeap(a,1,--l);
        }
}


int main(){
    int a[500001],n;
    ifstream fin("algsort.in");
    ofstream fout("algsort.out");
    fin>>n;
    for(int i=1;i<=n;++i)
        fin>>a[i];
    fin.close();
    heapSort(a,n);
    for(int i=1;i<=n;++i)
        fout<<a[i]<<' ';
    return 0;
}