Cod sursa(job #1809410)

Utilizator gorneanu.andreiFMI Gorneanu Andrei gorneanu.andrei Data 18 noiembrie 2016 22:00:20
Problema Sortare prin comparare Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.38 kb
#include <stdio.h>
#define MAXN 800001
int heap[MAXN],n;

void heapify(){

    FILE *f;
    f=fopen("algsort.in","r");
    fscanf(f,"%d",&n);
    int i, j, aux;
    fscanf(f,"%d",&heap[1]);

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

void sort(){

    int i, aux, m;
    m = n;

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

int main(){

    int i;
    FILE *g;
    g=fopen("algsort.out","w");

    heapify();
    sort();

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



    return 0;
}