Skip to content

Instantly share code, notes, and snippets.

@zitmen
Last active December 16, 2015 00:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zitmen/5346361 to your computer and use it in GitHub Desktop.
Save zitmen/5346361 to your computer and use it in GitHub Desktop.
Binary Heap - very simple, but works correctly and fast
#ifndef __BINARY_HEAP_H__
#define __BINARY_HEAP_H__
#include <exception>
#include <ostream>
using std::exception;
using std::ostream;
template<typename T>
class BinaryHeap
{
private:
int m_capacity;
int m_size;
T *m_data;
protected:
void heapify(int index)
{
int l = left(index), r = right(index), max = index, tmp;
if((l < m_size) && (m_data[l] > m_data[max])) max = l;
if((r < m_size) && (m_data[r] > m_data[max])) max = r;
if(max != index) { tmp = m_data[index]; m_data[index] = m_data[max]; m_data[max] = tmp; heapify(max); }
}
inline int left(int index)
{
return 2*index + 1;
}
inline int right(int index)
{
return 2*index + 2;
}
inline int parent(int index)
{
return ((index == 1) ? 0 : (index/2 - 1));
}
public:
Heap(int capacity)
{
m_size = 0;
m_capacity = capacity;
m_data = new T[m_capacity];
}
~Heap()
{
delete [] m_data;
}
void build_heap(T *arr, int count, bool copy = true) // deletes all the data!
{
if(count > m_capacity) throw exception("Heap has limited capacity!");
if(copy)
{
for(int i = 0; i < m_size; i++)
m_data[i] = arr[i];
}
else
{
m_data = arr;
}
m_size = count;
//
for(int i = m_size/2 - 1; i >= 0; i--)
heapify(i);
}
void push(const T &item)
{
static int i, p;
if(m_size == m_capacity) throw exception("Heap is full!");
m_data[i=m_size] = item;
m_size++;
while((i > 0) && (m_data[p=parent(i)] < item))
{
m_data[i] = m_data[p];
i = p;
}
m_data[i] = item;
}
inline void insert(T *arr, int count)
{
for(int i = 0; i < count; i++)
push(arr[i]);
}
inline T pop()
{
static T retval;
if(m_size == 0) throw exception("Heap is empty!");
retval = m_data[0];
m_size--;
m_data[0] = m_data[m_size];
heapify(0);
return retval;
}
inline T top() const
{
return m_data[0];
}
inline int size() const
{
return m_size;
}
inline int capacity() const
{
return m_capacity;
}
inline bool m_empty() const
{
return (size == 0);
}
inline bool full() const
{
return (m_size == m_capacity);
}
inline void clear()
{
m_size = 0;
}
friend ostream & operator<<(ostream &os, const Heap &heap)
{
for(int i = 0; i < heap.m_size; i++)
os << heap.m_data[i] << ' ';
return os;
}
};
#endif // __BINARY_HEAP_H__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment