Head file:
#pragma once
#ifndef _BINARY_HEAP_
#define _BINARY_HEAP_
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <stdexcept>
using namespace std;
template <typename elemType>
class BinaryHeap
{
public:
BinaryHeap() = default;
BinaryHeap(const vector<elemType> &items, bool(*comp)(const elemType &, const elemType &))
{
currentSize = items.size();
arry.resize(items.size() + 10);
for (int i = 0; i < items.size(); ++i)
arry[i + 1] = items[i];
compare = comp;
buildHeap();
}
void assignFunc(bool(*comp)(const elemType &, const elemType &)) { compare = comp; }
bool isEmpty() const { return currentSize == 0; }
const elemType &findTop() const
{
if (isEmpty())
throw runtime_error("No element in Heap");
return arry[1];
}
void insert(const elemType &x)
{
if (currentSize == arry.size() - 1)
arry.resize(arry.size() * 2);
int hole = ++currentSize;
arry[hole] = x;
percolateUp(hole);
}
void deleteTop()
{
if (isEmpty())
throw runtime_error("No element in Heap");
arry[1] = arry[currentSize--];
percolateDown(1);
}
void deleteTop(elemType &minItem)
{
if (isEmpty())
throw runtime_error("No element in Heap");
minItem = arry[1];
arry[1] = arry[currentSize--];
percolateDown(1);
}
void decreaseKey(elemType item, elemType changed)
{
int i = 1;
for (; i <= currentSize; ++i)
{
if (arry[i] == item)
break;
}
if (i > currentSize)
throw runtime_error("Not Exist");
arry[i] = changed;
percolateUp(i);
}
void increaseKey(elemType item, elemType changed)
{
int i = 1;
for (; i <= currentSize; ++i)
{
if (arry[i] == item)
break;
}
if (i > currentSize)
throw runtime_error("Not Exist");
arry[i] = changed;
percolateDown(i);
}
size_t pos(const elemType &item)
{
int i = 1;
for (; i <= currentSize; ++i)
if (arry[i] == item)
break;
return i;
}
private:
int currentSize;
vector<elemType> arry;
bool(*compare)(const elemType &, const elemType &);
void buildHeap()
{
for (int i = currentSize / 2; i > 0; --i)
percolateDown(i);
}
void percolateDown(int hole)
{
int child;
for (; hole <= currentSize; hole = child)
{
child = hole * 2;
if (child < currentSize && compare(arry[child + 1], arry[child]))
++child;
if (child <= currentSize && compare(arry[child], arry[hole]))
swap(arry[hole], arry[child]);
else
break;
}
}
void percolateUp(int hole)
{
for (; hole > 1 && compare(arry[hole], arry[hole / 2]); hole /= 2)
swap(arry[hole], arry[hole / 2]);
}
};
#endif
Main file:
#include "binary_heap.h"
#include <Windows.h>
using namespace std;
bool less1(const int &a, const int &b)
{
return a < b;
}
int main()
{
vector<int> arry = {8, 12, 9, 7, 22, 3, 26, 14, 11, 15};
BinaryHeap<int> bh(arry, less1);
bh.insert(1);
bh.deleteTop();
bh.deleteTop();
cout << bh.findTop() << endl;
system("PAUSE");
return 0;
}