Pagini recente » Cod sursa (job #2194085) | Cod sursa (job #1264670) | Cod sursa (job #2288829) | Cod sursa (job #52553) | Cod sursa (job #2642330)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
const int KMAX = 500001;
int heap[KMAX], heapSize;
int Parent(const int& node) {
return node / 2;
}
void Insert(const int& value) {
heap[++heapSize] = value;
int ptr = heapSize;
while(ptr != 1 && heap[ptr] < heap[ Parent(ptr) ]) {
swap(heap[ptr], heap[ Parent(ptr) ]);
ptr /= 2;
}
}
void Delete() {
if(heapSize == 1) {
heapSize--;
return;
}
swap(heap[1], heap[heapSize]);
heapSize--;
int ptr = 1;
bool isHeap = false;
while(!isHeap && 2 * ptr <= heapSize) {
if(2 * ptr + 1 <= heapSize) {
if(heap[ptr] <= min(heap[2 * ptr], heap[2 * ptr + 1]))
isHeap = true;
else if(heap[2 * ptr] <= heap[2 * ptr + 1]) {
swap(heap[ptr], heap[2 * ptr]);
ptr *= 2;
}else {
swap(heap[ptr], heap[2 * ptr + 1]);
ptr = ptr * 2 + 1;
}
}else {
if(heap[ptr] <= heap[2 * ptr]) {
isHeap = true;
} else {
swap(heap[ptr], heap[2 * ptr]);
ptr *= 2;
}
}
}
}
int main() {
int n;
f >> n;
for(int i = 1;i <= n;++i) {
int x;
f >> x;
Insert(x);
}
while(heapSize) {
g << heap[1] << ' ';
Delete();
}
return 0;
}