Pagini recente » Cod sursa (job #2649628) | Cod sursa (job #248128) | Cod sursa (job #2875858) | Cod sursa (job #2720703) | Cod sursa (job #2215857)
#include<cstdio>
#define MAX_N 500000
using namespace std;
int heap[MAX_N+1], n, heapSize;
inline void insertHeap(int x) {
int i, tmp;
heap[++heapSize] = x;
i = heapSize;
while(i >= 1 && heap[i] < heap[i/2]) {
tmp = heap[i];
heap[i] = heap[i/2];
heap[i/2] = tmp;
i >>= 1;
}
}
inline void Swap(int i, int j) {
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
void downHeap(int i) {
int leftSon, rightSon;
if(2*i <= heapSize) {
leftSon = heap[2*i];
if(2*i + 1 <= heapSize)
rightSon = heap[2*i+1];
else rightSon = 1 + leftSon;
if(leftSon <= rightSon) {
if(heap[i] > leftSon) {
Swap(i,2*i);
downHeap(2*i);
}
} else if(heap[i] > rightSon) {
Swap(i,2*i+1);
downHeap(2*i+1);
}
}
}
void heapSort(int n) {
FILE* fout = fopen("algsort.out","w");
for(int i = 1; i <= n; i++) {
fprintf(fout,"%d ",heap[1]);
heap[1] = heap[heapSize];
heapSize--;
downHeap(1);
}
fprintf(fout,"\n");
fclose(fout);
}
void read() {
int x;
FILE* fin = fopen("algsort.in","r");
fscanf(fin,"%d",&n);
for(int i = 1; i <= n; i++) {
fscanf(fin,"%d",&x);
insertHeap(x);
}
fclose(fin);
}
int main() {
read();
heapSort(n);
return 0;
}