Pagini recente » Cod sursa (job #994470) | Cod sursa (job #562326) | Cod sursa (job #2930857) | Cod sursa (job #1892097) | Cod sursa (job #1809431)
#include <stdio.h>
#define MAXN 1000001
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 > 1){
aux = heap[1];
heap[1] = heap[n];
heap[n] = aux;
--n;
i = 1;
while((heap[i] < heap[2 * i] && i <= n / 2) || (heap[i] < heap[2 * i + 1] && 2 * i + 1 <=n) && i <= n / 2){
if(2 * i + 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{if(i * 2 + 1 <= n)
{aux = heap[2 * i + 1];
heap[2 * i + 1]= heap[i];
heap[i] = aux;
i = i * 2 + 1;}
}
}
else{
aux = heap[2 * i];
heap[2 * i] = heap[i];
heap[i] = aux;
i = i * 2;
}
}
}
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;
}