A binary heap is a complete binary tree stored in an array where every parent is ordered relative to its children. In a min heap the smallest element is at the root; in a max heap the largest. Heaps give O(1) access to the extreme value and O(log n) insert and delete, powering priority queues and heap sort. This section covers the representation, both heap types, insertion, deletion, heapify, and bottom-up construction.
Index math is the structure.
Parent (i - 1) / 2, children 2i + 1 and 2i + 2. Get these right and the rest follows.
Path
Learning Path
Work through the stages in order, or jump to a topic from the index below (8 tutorials).
A heap array is not sorted; only the root is guaranteed to be the extreme.
index
Mixing 0- and 1-based formulas
Use 2i + 1/2i + 2 for 0-based arrays.
size
Forgetting to track size
Pass the current element count to every function.
Remember
Key Takeaways
Complete tree in an array.
Parent beats children.
Insert and delete O(log n).
One line: A binary heap is a complete binary tree stored in an array where every parent is ordered relative to its children.
Frequently Asked Questions
In data structures, a binary heap is a complete binary tree stored in an array where each parent is ordered with respect to its children. (It is unrelated to the malloc heap.)
A min heap keeps the smallest value at the root; a max heap keeps the largest.
Priority queues, heap sort, and algorithms such as Dijkstra's shortest path.