[priority-queue] Optimize heap access

This commit is contained in:
Behdad Esfahbod 2022-05-18 16:17:16 -06:00
parent 9308659fd7
commit 39a424caf0
2 changed files with 12 additions and 14 deletions

View File

@ -63,9 +63,11 @@ struct hb_priority_queue_t
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);
bubble_down (0);
@ -104,6 +106,8 @@ struct hb_priority_queue_t
void bubble_down (unsigned index)
{
assert (index <= heap.length);
unsigned left = left_child (index);
unsigned right = right_child (index);
@ -113,11 +117,11 @@ struct hb_priority_queue_t
return;
bool has_right = right < heap.length;
if (heap[index].first <= heap[left].first
&& (!has_right || heap[index].first <= heap[right].first))
if (heap.arrayZ[index].first <= heap.arrayZ[left].first
&& (!has_right || heap[index].first <= heap.arrayZ[right].first))
return;
if (!has_right || heap[left].first < heap[right].first)
if (!has_right || heap.arrayZ[left].first < heap.arrayZ[right].first)
{
swap (index, left);
bubble_down (left);
@ -130,10 +134,12 @@ struct hb_priority_queue_t
void bubble_up (unsigned index)
{
assert (index <= heap.length);
if (index == 0) return;
unsigned parent_index = parent (index);
if (heap[parent_index].first <= heap[index].first)
if (heap.arrayZ[parent_index].first <= heap.arrayZ[index].first)
return;
swap (index, parent_index);

View File

@ -73,17 +73,9 @@ test_extract ()
assert (queue.is_empty ());
}
static void
test_extract_empty ()
{
hb_priority_queue_t queue;
assert (queue.pop_minimum () == hb_pair (0, 0));
}
int
main (int argc, char **argv)
{
test_insert ();
test_extract ();
test_extract_empty ();
}