Cod sursa(job #1945915)

Utilizator Horia14Horia Banciu Horia14 Data 29 martie 2017 19:15:32
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include<cstdio>
#define N_MAX 500000
using namespace std;

int v[N_MAX+1], heap[N_MAX+1], n;
FILE *fout = fopen("algsort.out","w");

void Read()
{
    FILE *fin = fopen("algsort.in","r");
    fscanf(fin,"%d",&n);
    for(int i=1; i<=n; i++)
    {
        fscanf(fin,"%d",&v[i]);
        heap[i] = v[i];
    }
    fclose(fin);
}

void Swap(int x, int y)
{
    int aux = heap[x];
    heap[x] = heap[y];
    heap[y] = aux;
}

void CombHeap(int i)
{
    int son, father;
    father = i; son = 2*i;
    while(son <= n)
    {
        if(son+1 <= n)
            son = heap[son] < heap[son+1] ? son:son+1;
        if(heap[father] > heap[son])
        {
            Swap(father,son);
            father = son;
            son*=2;
        }
        else son = n+1;
    }
}

void BuildHeap()
{
    for(int i=n/2; i>=1; i--)
        CombHeap(i);
}

void ExtractMin()
{
    int son, father;
    heap[1] = heap[n];
    n--;
    father = 1; son = 2;
    while(son <= n)
    {
        if(son+1 <= n)
            son = heap[son] < heap[son+1] ? son:son+1;
        if(heap[father] > heap[son])
        {
            Swap(father,son);
            father = son;
            son*=2;
        }
        else son = n+1;
    }
}

void HeapSort()
{
    while(n > 0)
    {
        fprintf(fout,"%d ",heap[1]);
        ExtractMin();
    }
}

int main()
{
    Read();
    BuildHeap();
    HeapSort();
    return 0;
}