Pagini recente » Cod sursa (job #2173791) | Cod sursa (job #1960144) | Cod sursa (job #231636) | Cod sursa (job #239040) | Cod sursa (job #2217740)
#include<cstdio>
#define MAX_N 500000
using namespace std;
int heap[MAX_N+1], n;
FILE* fout = fopen("algsort.out","w");
void read() {
FILE* fin = fopen("algsort.in","r");
fscanf(fin,"%d",&n);
for(int i = 1; i <= n; i++)
fscanf(fin,"%d",&heap[i]);
fclose(fin);
}
inline void Swap(int i, int j) {
int aux = heap[i];
heap[i] = heap[j];
heap[j] = aux;
}
void heapDown(int i, int heapSize) {
int l, r, ind;
l = i << 1;
r = (i << 1) + 1;
if(l <= heapSize && heap[i] > heap[l])
ind = l;
else ind = i;
if(r <= heapSize && heap[ind] > heap[r])
ind = r;
if(ind != i) {
Swap(i,ind);
heapDown(ind,heapSize);
}
}
void buildHeap(int n) {
for(int i = n/2; i >= 1; i--)
heapDown(i,n);
}
void heapSort(int n) {
while(n) {
fprintf(fout,"%d ",heap[1]);
Swap(1,n);
n--;
heapDown(1,n);
}
fprintf(fout,"\n");
fclose(fout);
}
int main() {
read();
buildHeap(n);
heapSort(n);
return 0;
}