Cod sursa(job #1905912)

Utilizator bogdanboboc97Bogdan Boboc bogdanboboc97 Data 6 martie 2017 11:37:27
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <iostream>
#include <fstream>
#include <vector>

template<typename DataType>
class Heap{
private:
    std::vector< DataType > heap;

public:

    void push(DataType value)//push a element in heap
    {
        heap.push_back(value);
        for(int v = heap.size()-1 ; v != 0; v = (v-1)/2)
        {
            if(heap[v] < heap[(v-1)/2])
                std::swap(heap[v],heap[(v-1)/2]);
            else
                break;
        }
    }

    size_t size()//number of elements in heap
    {
        return heap.size();
    }

    DataType top()//return the top of the heap
    {
        return heap[0];
    }

    void pop()//delete the top of the heap
    {
        std::swap(heap[0],heap[ heap.size()-1 ]);
        heap.pop_back();
        int v=0;
        while(true)
        {
            if((2*v+1<(int)heap.size() && heap[2*v+1] < heap[v]) && (2*v+2>=(int)heap.size() || !(heap[2*v+2] < heap[2*v+1])))
            {
                std::swap(heap[v],heap[2*v+1]);
                v=2*v+1;
                continue;
            }
            if((2*v+2<(int)heap.size() && heap[2*v+2] < heap[v] && heap[2*v+2] < heap[2*v+1]))
            {
                std::swap(heap[v],heap[2*v+2]);
                v=2*v+2;
                continue;
            }
            break;
        }
    }
};

template<typename DataType>
void heapSort(std::vector< DataType > &arr)
{
    Heap< DataType > H;
    while(arr.size())
    {
        H.push(arr[ arr.size()-1 ]);
        arr.pop_back();
    }
    while(H.size())
    {
        arr.push_back(H.top());
        H.pop();
    }
}
int main()
{
    int n;
    std::vector<int> arr;

    std::ifstream in("algsort.in");

    in>>n;
    for(int i=0;i<n;i++)
    {
        int x;
        in>>x;
        arr.push_back(x);
    }

    in.close();

    heapSort(arr);

    std::ofstream out("algsort.out");

    for(int i=0;i<n;i++)
        out<<arr[i]<<' ';
    out<<'\n';

    out.close();

    return 0;
}