Heap (data structure)
In computer science, a heap is a type of tree (data structure) that satisfies the heap property. Heaps are useful when you need to remove the item with the highest (or lowest) value. A common implementation of a heap is the binary heap in which the tree is a complete binary tree.
Heap property[change | change source]
- In a max-heap, the value of each item is less than or equal to the value of its parent, with the maximum-value item at the root.
- In a min-heap, the value of each item is greater than or equal to the value of its parent, with the minimum-value item at the root.
Operations[change | change source]
- find: return a maximum item of a max-heap or a minimum item of a min-heap.
- insert: add a new item to the heap.
- extract: returns the maximum item from a max-heap (or minimum item from a min-heap) after removing it.
- delete: removes the root of a max-heap (or min-heap).
- size: return the number of items in the heap.
- is-empty: return true if the heap is empty, false otherwise.
Maintaining the heap property[change | change source]
- insert: insert the item at the bottom rightmost location; swap the item with its parent until the heap property is preserved.
- delete: remove the root; swap it with the item at the bottom rightmost location; swap the new root downwards with the smaller of its children (for a min-heap) until the heap property is preserved.
References[change | change source]
- Adamchik, Victor. "Binary Heap". Computer Science - 121 Fall 2009. CMU. Retrieved 11 October 2020.