Cod sursa(job #2739679)

Utilizator serafimalex2001Serafim Alex serafimalex2001 Data 9 aprilie 2021 13:07:45
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

vector<int> v;
int n;

void SiftUp(vector<int> &v, int N, int i){
    int father = (i-1)/2;
    while(father >= 0){
       if(v[i] < v[father])
       {
           swap(v[i],v[father]);
           i = father;
           father = (i-1)/2;
       }
       else break;
    }
}

void SiftDown(vector<int> &v, int N, int i){
    int son = i*2+1;
    while(son < N){
        if(son + 1 < N && v[son+1] < v[son])
            son++;
        if(v[i] <= v[son])
            break;
        swap(v[i], v[son]);
        i = son;
        son = i*2+1;
    }
}

void Read(){
    int i,j;
    fin >> n;
    for(int i = 0; i<n; ++i){
        fin>>j;
        v.push_back(j);
        SiftUp(v, i+1, i);
    }
}

void Do(){
    int i,j;
    i = n;
    while(i > 0){
        fout << v[0] << " ";
        i--;
        swap(v[0], v[i]);
        SiftDown(v, i, 0);
    }
}

int main()
{
    Read();
    Do();
    return 0;
}