Cod sursa(job #2847060)

Utilizator rapidu36Victor Manz rapidu36 Data 10 februarie 2022 09:41:54
Problema Sortare prin comparare Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <stdio.h>
#include <stdlib.h>
#define N 500001

int h[N], nh, n;

void coboara(int p)
{
    int fs = 2*p, fd = 2*p + 1, optim = p;
    if (fs <= nh && h[fs] > h[optim])
    {
        optim = fs;
    }
    if (fd <= nh && h[fd] > h[optim])
    {
        optim = fd;
    }
    if (optim != p)
    {
        int aux = h[optim];
        h[optim] = h[p];
        h[p] = aux;
        coboara(optim);
    }
}

void heap_sort()
{
    nh = n;
    for (int i = (n + 1) / 2; i >= 1; i--)
    {
        coboara(i);
    }
    for (int i = n; i > 1; i--)
    {
        int aux = h[i];
        h[i] = h[1];;
        h[1] = aux;
        nh--;
        coboara(1);
    }
}

int main()
{
    FILE *in, *out;
    in = fopen("algsort.in", "r");
    out = fopen("algsort.out", "w");
    fscanf(in, "%d", &n);
    for (int i = 1; i <= n; i++)
    {
        fscanf(in, "%d", &h[i]);
    }
    fclose(in);
    heap_sort();
    for (int i = 1; i <= n; i++)
    {
        fprintf(out, "%d ", h[i]);
    }
    fclose(out);
    return 0;
}