Cod sursa(job #1414936)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 3 aprilie 2015 12:46:09
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <stdio.h>

#define MAX_N 500000

int a[MAX_N];
int hSize;
inline void downHeap(int nod) {
  int smallest, changed;

  do {
    changed = 0;
    if (nod * 2 + 1 < hSize && a[nod * 2 + 1] < a[nod]) {
      smallest = nod * 2 + 1;
    } else {
      smallest = nod;
    }
    if (nod * 2 + 2 < hSize && a[nod * 2 + 2] < a[smallest]) {
      smallest = nod * 2 + 2;
    }
    if (smallest != nod) {
      int t = a[smallest];
      a[smallest] = a[nod];
      a[nod] = t;
      nod = smallest;
      changed = 1;
    }
  } while (changed);
}
int main(void) {
  FILE *f;
  int n;
  int i;

  f = fopen("algsort.in", "r");
  fscanf(f, "%d", &n);
  for (i = 0; i != n; i++) {
    fscanf(f, "%d", &a[i]);
  }
  fclose(f);
  hSize = n;
  for (i = (n >> 1) - 1; i >= 0; i--) {
    downHeap(i);
  }
  f = fopen("algsort.out", "w");
  hSize = n;
  for (; n; n--) {
    fprintf(f, "%d ", a[0]);
    a[0] = a[--hSize];
    downHeap(0);
  }
  fclose(f);
  return 0;
}