Cod sursa(job #2381623)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 17 martie 2019 11:02:04
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int i,n,v[500001],k;
void swap(int &a,int &b){
    int c=a;
    a=b;
    b=c;
}
void down_heap(int poz,int n){
    while(poz*2<=n){
        int st=poz*2;
        if(st+1<=n&&v[st+1]>v[st])
            st=st+1;
        if(v[poz]<v[st]){
            swap(v[poz],v[st]);
            poz=st;
        }
        else
            return;
    }
}
void up_heap(int poz){
    while(poz/2>=1){
        int st=poz/2;
        if(v[poz]>v[st]){
            swap(v[poz],v[st]);
            poz=st;
        }
        else
            return;
    }
}
void sort_heap(){
    for(int i=n/2;i>=1;i--)
        down_heap(i,n);
}
int main()
{   f>>n;
    for(i=1;i<=n;i++)
        f>>v[i];
    sort_heap();
    k=n;
    for(i=1;i<n;i++){
        swap(v[1],v[k]);
        k--;
        down_heap(1,k);
    }
    for(i=1;i<=n;i++)
        g<<v[i]<<' ';
    return 0;
}