[priority-queue] Optimize heap access
This commit is contained in:
parent
9308659fd7
commit
39a424caf0
|
@ -63,9 +63,11 @@ struct hb_priority_queue_t
|
||||||
|
|
||||||
item_t pop_minimum ()
|
item_t pop_minimum ()
|
||||||
{
|
{
|
||||||
item_t result = heap[0];
|
assert (!is_empty ());
|
||||||
|
|
||||||
heap[0] = heap[heap.length - 1];
|
item_t result = heap.arrayZ[0];
|
||||||
|
|
||||||
|
heap.arrayZ[0] = heap.arrayZ[heap.length - 1];
|
||||||
heap.shrink (heap.length - 1);
|
heap.shrink (heap.length - 1);
|
||||||
bubble_down (0);
|
bubble_down (0);
|
||||||
|
|
||||||
|
@ -104,6 +106,8 @@ struct hb_priority_queue_t
|
||||||
|
|
||||||
void bubble_down (unsigned index)
|
void bubble_down (unsigned index)
|
||||||
{
|
{
|
||||||
|
assert (index <= heap.length);
|
||||||
|
|
||||||
unsigned left = left_child (index);
|
unsigned left = left_child (index);
|
||||||
unsigned right = right_child (index);
|
unsigned right = right_child (index);
|
||||||
|
|
||||||
|
@ -113,11 +117,11 @@ struct hb_priority_queue_t
|
||||||
return;
|
return;
|
||||||
|
|
||||||
bool has_right = right < heap.length;
|
bool has_right = right < heap.length;
|
||||||
if (heap[index].first <= heap[left].first
|
if (heap.arrayZ[index].first <= heap.arrayZ[left].first
|
||||||
&& (!has_right || heap[index].first <= heap[right].first))
|
&& (!has_right || heap[index].first <= heap.arrayZ[right].first))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
if (!has_right || heap[left].first < heap[right].first)
|
if (!has_right || heap.arrayZ[left].first < heap.arrayZ[right].first)
|
||||||
{
|
{
|
||||||
swap (index, left);
|
swap (index, left);
|
||||||
bubble_down (left);
|
bubble_down (left);
|
||||||
|
@ -130,10 +134,12 @@ struct hb_priority_queue_t
|
||||||
|
|
||||||
void bubble_up (unsigned index)
|
void bubble_up (unsigned index)
|
||||||
{
|
{
|
||||||
|
assert (index <= heap.length);
|
||||||
|
|
||||||
if (index == 0) return;
|
if (index == 0) return;
|
||||||
|
|
||||||
unsigned parent_index = parent (index);
|
unsigned parent_index = parent (index);
|
||||||
if (heap[parent_index].first <= heap[index].first)
|
if (heap.arrayZ[parent_index].first <= heap.arrayZ[index].first)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
swap (index, parent_index);
|
swap (index, parent_index);
|
||||||
|
|
|
@ -73,17 +73,9 @@ test_extract ()
|
||||||
assert (queue.is_empty ());
|
assert (queue.is_empty ());
|
||||||
}
|
}
|
||||||
|
|
||||||
static void
|
|
||||||
test_extract_empty ()
|
|
||||||
{
|
|
||||||
hb_priority_queue_t queue;
|
|
||||||
assert (queue.pop_minimum () == hb_pair (0, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
int
|
int
|
||||||
main (int argc, char **argv)
|
main (int argc, char **argv)
|
||||||
{
|
{
|
||||||
test_insert ();
|
test_insert ();
|
||||||
test_extract ();
|
test_extract ();
|
||||||
test_extract_empty ();
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue