heap overview

A heap is a tree in which every node's key is greater than or equal to, or less than or equal to, its parent's key.

A heap in which every node's key is greater than or equal to its parent's key is called a min-heap; otherwise it is called a max-heap. STL's priority_queue is in fact a max-heap.

The main operations supported by a (min-)heap are: inserting a number, querying the minimum, deleting the minimum, merging two heaps, and decreasing the value of an element.

Some powerful heaps (mergeable heaps) can also efficiently support operations such as \.

Even more powerful heaps also support persistence, meaning that any historical version can be queried or operated on to produce a new version.

Heap classifications

Operation Data structure1Pairing heapBinary heapLeftist treeBinomial heapFibonacci heap
Insert (insert)O(1)O(1)O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)2O(1)O(1)
Find minimum (find-min)O(1)O(1)O(1)O(1)O(1)O(1)O(1)O(1)34O(1)O(1)
Delete minimum (delete-min)O(log⁡n)O(\log n)4O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)4
Merge (merge)O(1)O(1)O(n)O(n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(1)O(1)
Decrease an element's value (decrease-key)o(log⁡n)o(\log n) (lower bound Ω(log⁡log⁡n)\Omega(\log \log n), upper bound O(22log⁡log⁡n)O(2^{2\sqrt{\log \log n}}))4O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(1)O(1)4
Supports persistence×\times✓\checkmark✓\checkmark✓\checkmark×\times

By convention, an unqualified reference to a “heap” usually means a binary heap.

Footnotes

  1. Table from Wikipedia ↩

  2. The complexity of a single insertion is O(log⁡n)O(\log n), but for kk consecutive insertions, a binomial heap containing only the elements to be inserted can be created and then merged with the original binomial heap, giving an amortized complexity of O(1)O(1). ↩

  3. A pointer to the minimum element can be maintained, and that pointer can be updated during other operations, allowing queries in O(1)O(1) time. ↩

  4. Amortized complexity. ↩ ↩2 ↩3 ↩4 ↩5

This content comes from OI Wiki: heap overview. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.