Cod sursa(job #1808640)

Utilizator gorneanu.andreiFMI Gorneanu Andrei gorneanu.andrei Data 17 noiembrie 2016 22:07:09
Problema Sortare prin comparare Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.24 kb
#include <stdio.h>
#define MAXN 700001
int heap[MAXN];

int main(){

    int n, i, m = 0, aux, j, k;
    FILE *f, *g;
    f=fopen("algsort.in","r");
    g=fopen("algsort.out","w");

    fscanf(f,"%d",&n);
    fscanf(f,"%d",&heap[1]);
    for(i = 2;i <= n; ++i){
            fscanf(f,"%d",&heap[i]);
            j = i;
        while(heap[j] > heap[j / 2]){
                aux = heap[i];
                heap[i] = heap[i / 2];
                heap[i / 2] = aux;
                j = j / 2;
            }
    }
    m = n;

    while(n > 1){
        aux = heap[1];
        heap[1] = heap[n];
        heap[n] = aux;
        --n;
        j = 1;
        while((heap[j] < heap[j * 2] && j * 2 <= n) || (heap[j] < heap[j * 2 + 1] && 2 * j + 1 <= n))
        {
            if(heap[j * 2] > heap[j * 2 + 1]){
               aux = heap[j];
               heap[j] = heap[j * 2];
               heap[j * 2] = aux;
               j = j * 2;
               }
               else{
               aux = heap[j];
               heap[j] = heap[j * 2 + 1];
               heap[j * 2 + 1] = aux;
               j = j * 2 + 1;
               }
        }
    }

        for(i = 1;i <= m; ++i)
            fprintf(g,"%d ",heap[i]);

return 0;
}