Last active
December 14, 2015 23:29
-
-
Save weidagang/5166351 to your computer and use it in GitHub Desktop.
Binary heap structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Node { | |
int m_value; | |
int m_row; | |
int m_column; | |
Node() { | |
} | |
Node(int value, int row, int column) { | |
m_value = value; | |
m_row = row; | |
m_column = column; | |
} | |
}; | |
class BinaryHeap { | |
private: | |
const unsigned int m_capacity; | |
Node* const m_nodes; | |
unsigned int m_size; | |
public: | |
BinaryHeap(unsigned int capacity) : | |
m_capacity(capacity) | |
, m_nodes(new Node[capacity]) | |
{ | |
m_size = 0; | |
} | |
~BinaryHeap() { | |
delete m_nodes; | |
} | |
int insert(Node& node) { | |
if (m_size >= m_capacity) { | |
return ERROR; | |
} | |
m_nodes[m_size++] = node; | |
_adjust_insert(); | |
} | |
int pop(Node& out_node) { | |
if (m_size <= 0) { | |
return ERROR; | |
} | |
out_node = m_nodes[0]; | |
std::swap(m_nodes[0], m_nodes[m_size - 1]); | |
--m_size; | |
_adjust_pop(); | |
} | |
private: | |
void _adjust_insert() { | |
int idx = m_size - 1; | |
while (idx > 0) { | |
int parent = (idx - 1) / 2; | |
if (m_nodes[parent].m_value > m_nodes[idx].m_value) { | |
std::swap(m_nodes[parent], m_nodes[idx]); | |
idx = parent; | |
} | |
else { | |
break; | |
} | |
} | |
} | |
void _adjust_pop() { | |
int idx = 0; | |
while (idx < m_size) { | |
int min_idx = idx; | |
int left = idx * 2 + 1; | |
if (left < m_size && m_nodes[left].m_value < m_nodes[min_idx].m_value) { | |
min_idx = left; | |
} | |
int right = idx * 2 + 2; | |
if (right < m_size && m_nodes[right].m_value < m_nodes[min_idx].m_value) { | |
min_idx = right; | |
} | |
if (min_idx == idx) { | |
break; | |
} | |
else { | |
std::swap(m_nodes[idx], m_nodes[min_idx]); | |
idx = min_idx; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment