Pagini recente » Cod sursa (job #1616137) | Cod sursa (job #2718403) | Cod sursa (job #1322630) | Cod sursa (job #2435929) | Cod sursa (job #2083052)
#include <fstream>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int n,heap[500010],m;
void add(int val){
heap[++n] = val;
int pos = n;
while(pos != 1 && heap[pos] < heap[pos/2]){
swap(heap[pos],heap[pos/2]);
pos /= 2;
}
}
void deletepos(int pos){
swap(heap[pos],heap[n]);
--n;
while(pos<=n){
int best = 0,mx = heap[pos];
if(2*pos <= n && mx > heap[2*pos]){
mx = heap[2*pos];
best = 1;
}
if(2*pos+1 <= n && mx > heap[2*pos+1]){
mx = heap[2*pos+1];
best = 2;
}
if(best == 0) break;
else if(best == 1){
swap(heap[pos],heap[2*pos]);
pos *= 2;
}
else{
swap(heap[pos],heap[2*pos+1]);
pos = pos*2+1;
}
}
}
int main()
{
int i,nr;
fin>>m;
for(i = 0 ; i < m; i++){
fin>>nr;
add(nr);
}
for(i = 1 ; i <= m; i++){
fout<<heap[1]<<" ";
deletepos(1);
}
}