Pagini recente » Cod sursa (job #2563953) | Cod sursa (job #2008760) | Cod sursa (job #1243456) | Cod sursa (job #2150329) | Cod sursa (job #2079282)
///HEAPSORT
#include<cstdio>
#include<algorithm>
using namespace std;
int i, heap[500001], n, x, lgHeap;
void heap_up(int poz){
while (poz>1) {
if (heap[poz]<heap[poz/2]) {swap(heap[poz], heap[poz/2]); poz/=2;}
else break;
}
}
void heap_down(int poz){
int son;
while (2*poz<=lgHeap) {
if (2*poz+1>lgHeap) son=2*poz;
else {if (heap[2*poz]<=heap[2*poz+1]) son=2*poz; else son=2*poz+1;}
if (heap[son]<heap[poz]) {swap(heap[son], heap[poz]); poz=son;}
else return;
}
}
int main(){
freopen("algsort.in","r",stdin);
freopen("algsort.out","w",stdout);
scanf("%d", &n);
for (i=1;i<=n;i++) {scanf("%d", &x); heap[++lgHeap]=x; heap_up(lgHeap);}
for (i=1;i<=n;i++) {
printf("%d ", heap[1]);
swap(heap[1], heap[lgHeap]);
lgHeap--;
heap_down(1);
}
return 0;
}