Pagini recente » Cod sursa (job #2437380) | Cod sursa (job #135194) | Cod sursa (job #2614522) | Cod sursa (job #765427) | Cod sursa (job #346894)
Cod sursa(job #346894)
#include <fstream>
#include <iostream>
#include <vector>
#include <limits>
#include <cmath>
#include <string>
using namespace std;
void reconstruct(int t,vector<int>& v,int n);
int main(){
ifstream in("algsort.in");
ofstream out("algsort.out");
int n;
in>>n;
vector<int> v;
v.reserve(n);
for(int i=0;i<n;++i){
int x;in>>x;
v.push_back(x);
if(v[0]>v[i]) swap(v[0],v[i]);
}
//forming the heap
for(int i=(n-1)/2;i>0;--i){
reconstruct(i,v,n);
}
while(n>2){
n--;
swap(v[1],v[n]);
reconstruct(1,v,n);
}
//cica ii gata
for(int i=0;i<v.size();i++){
out<<v[i]<<" ";
}
}
void reconstruct(int t,vector<int>& v,int n){
if(2*t<n-1){
if(v[t]<v[2*t]){
if(v[2*t]<v[2*t+1]){
swap(v[2*t+1],v[t]);reconstruct(2*t+1,v,n);
}else{
swap(v[2*t],v[t]);reconstruct(2*t,v,n);
}
}else if(v[t]<v[2*t+1]){
swap(v[2*t+1],v[t]);reconstruct(2*t+1,v,n);
}
}else if(2*t<n){
if(v[t]<v[2*t]){
swap(v[2*t],v[t]);reconstruct(2*t,v,n);
}
}
}