#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept>
using namespace std;
template<typename T>
class Heap
{
public:
Heap();
Heap(T elements[], int arraySize);
T remove() throw (runtime_error);
void add(T element);
int getSize();
private:
vector<T> v;
};
template <typename T>
Heap<T>::Heap()
{
}
template <typename T>
Heap<T>::Heap(T elements[], int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
add(elements[i]);
}
}
template <typename T>
T Heap<T>::remove() throw (runtime_error)
{
if (v.size() == 0)
throw runtime_error("Heap is empty");
T removedElement = v[0];
v[0] = v[v.size() - 1];
v.pop_back();
int currentIndex = 0;
while (currentIndex < v.size())
{
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
if (leftChildIndex >= v.size()) break;
int maxIndex = leftChildIndex;
if (rightChildIndex < v.size())
{
if (v[maxIndex] < v[rightChildIndex])
{
maxIndex = rightChildIndex;
}
}
if (v[currentIndex] < v[maxIndex])
{
T temp = v[maxIndex];
v[maxIndex] = v[currentIndex];
v[currentIndex] = temp;
currentIndex = maxIndex;
}
else
break;
}
return removedElement;
}
template <typename T>
void Heap<T>::add(T element)
{
v.push_back(element);
int currentIndex = v.size() - 1;
while (currentIndex > 0)
{
int parentIndex = (currentIndex - 1) / 2;
if (v[currentIndex] > v[parentIndex] > 0)
{
T temp = v[currentIndex];
v[currentIndex] = v[parentIndex];
v[parentIndex] = temp;
}
else
break;
currentIndex = parentIndex;
}
}
template <typename T>
int Heap<T>::getSize()
{
return v.size();
}
#endif