Skip to content

(Minimum / Maximum) Binary Heap

We'll focus on maximum binary heap.

Each element has a key (priority) and a value. The element with the highest key will be stored in the root. The element with the second-highest key will be stored as a direct child of the root. Once again, a min-heap is analogous.

Can we say anything about the element with the third-highest key?

Not really. It can either be the direct child of the root element, or the child of the second-highest element.

Invariant

  • Complete binary tree
    • "Flush top, flush left"
  • key of parent is greater than (or equal to) the key of child
    • Depends if you allow duplicate keys

Operations

Possible implementation of Priority Queue

  • insert: \(O(\log n)\)
  • extractMax: \(O(\log n)\)
    • peekMax: \(O(1)\)
  • decreaseKey/increaseKey: \(O(\log n)\) (expected) or \(O(n)\)
    • Depends if used in conjunction with a hash table
  • heapify: \(O(n)\)

Implementation

  • Even though it is visualised as a tree, the underlying representation is an array
  • Include a hash table to ensure \(O(1)\) expected time to find an element by value

Question: Why is heapify linear time?

Math