Menu

📰
0

Heap::PQ — A Binary Heap (Priority Queue) Implementation for Perl

DEV Community: perl·LNATION·about 1 month ago
#v6BjmFGu
#dev#class#code#heap#highlight#article
Reading 0:00
15s threshold

So What Is A Binary Heap? A binary heap is really just an sorted array pretending to be a tree. Each element has a parent and children, but instead of pointers you find them with simple array indexes. The trick is that every parent follows one rule relative to its children, and that rule decides what kind of heap you get: Min heap - every parent is less than or equal to its children. The smallest element always lives at the root/top. Max heap - every parent is greater than or equal to its children. The largest element always lives at the root/top. Because the tree is complete, the parent of element at index i sits at index floor((i−1)/2) , and its children sit at 2i+1 and 2i+2 . No pointers, no linked lists — just arithmetic on array indices. That cache friendly layout is one reason heaps are so fast in practice.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More