Cod sursa(job #1491145)

Utilizator bghimisFMI Ghimis Bogdan bghimis Data 24 septembrie 2015 20:47:32
Problema Sortare prin comparare Scor 60
Compilator c Status done
Runda Arhiva educationala Marime 1.59 kb
#include <stdio.h>
#include <stdlib.h>

int heap[200000];
int length;

void swap (int *a, int *b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

void sift_up (int idx) {
  if (idx == 0)
    return;
  
  int father = (idx - 1) / 2;
    
  if (heap[idx] < heap[father]) {
    swap (&heap[idx], &heap[father]);
    sift_up (father);
  }
}

void push_heap (int val) {
  heap[length++] = val;
  sift_up (length - 1);
}

void sift_down (int idx) {
  int fst_son = 2 * idx + 1;
  int snd_son = 2 * idx + 2;

  if (fst_son >= length)
    return;
  else if (snd_son >= length) {
    if (heap[idx] >= heap[fst_son])
      swap (&heap[idx], &heap[fst_son]);

    return;
  }

  if (heap[idx] > heap[fst_son] && heap[idx] > heap[snd_son]) {
    if (heap[fst_son] < heap[snd_son]) {
      swap (&heap[idx], &heap[fst_son]);
      sift_down (fst_son);
    }
    else {
      swap (&heap[idx], &heap[snd_son]);
      sift_down (snd_son);
    }
  } else {
    if (heap[idx] > heap[fst_son]) {
      swap (&heap[idx], &heap[fst_son]);
      sift_down (fst_son);
    } else if (heap[idx] >= heap[snd_son]) {
      swap (&heap[idx], &heap[snd_son]);
      sift_down (snd_son);      
    }     
  }    
}

int pop_heap () {
  int result = heap[0];

  heap[0] = heap[--length];
  sift_down(0);
  
  return result;
}

int main(int argc, char *argv[]) {
  freopen ("algsort.in", "r", stdin);
  freopen ("algsort.out", "w", stdout);
  
  int n;
  scanf ("%d", &n);

  int i;
  for (i = 0; i < n; ++i) {
    int x;
    scanf ("%d", &x);

    push_heap (x);
  }

  while (length != 0)
    printf ("%d ", pop_heap());

  printf ("\n");
  
  return 0;
}