Cod sursa(job #2642330)

Utilizator marius004scarlat marius marius004 Data 14 august 2020 18:59:50
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#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;
}