Binary Heap

A binary heap is a certain type of Binary Tree. Less strict than a binary tree, each node’s children needs to be smaller or bigger than the parent node. A Binary Heap is another way of implementing a Priority Queue.

A heap is a binary tree with the following two properties:

  • Structural Property: all levels of a heap are completely filled, except (possible) for the last level.
  • Heap-order Property: For any node , the key of the parent is larger than or equal to key of . max-heap Lemma: The height of a heap with nodes is

Run-time for creating binary heap:

  • using Heapify (bottom-up approach)
  • using insertion? (top bottom approach)

Storing Heaps in Array

Let be a heap of items and let be an array of size . We store the root in and continue with elements from top to bottom, in each level left-to-right.

  • root node at index
  • last node
  • left child node
  • right child node
  • parent node

Functions:

  • root()
  • last()
  • parent(i)

Operations in Binary Heaps

Insert

  • Place new key at the first free leaf
  • Perform fix-up since heap-order might be violated.

Time complexity of insert: (height of heap)

fix-up

Pseudocode:

deleteMax

  • The maximum item of a heap is at the root node
  • Replace the root by the last leaf (last leaf is taken out)
  • The heap-order property might be violated fix-down

Time complexity of deleteMax: (height of heap)

fix-down

Pseudocode:

  • small node from the top, swap with bigger node

Priority Queue Realization Using Heaps

  • Store items in array and globally keep track of size
  • insert and deleteMax time

Sorting using heaps

Remember from Priority Queue sorting have time: Using binary-heap to implement PQs we have:

  • since both insert and deleteMax run in time for heaps
  • PQ-Sort using heaps takes time.

Questions

  • Given an array of  elements, what are the possible runtimes for creating a binary heap from all the elements of  using the algorithms discussed in lecture?
    • Insertion (top-bottom)
    • Heapify
  • In a max-heap implemented as an array, an item with the smallest key must be the last valid item in the array.
    • False
  • In a max-heap implemented as an array, at least one of the leafs must be an item with the smallest key.
    • True
  • Given a max-heap of items (implemented as described in class) and a key value , the problem of searching for in can be solved in time.
    • False, it is using PQ-sort.
  • In a max-heap implemented as an array, an item with the smallest key may be the strict ancestor of some leaf node (i.e. not the leaf node itself).
    • True, but why?
  • In a max-heap implemented as an array, an item with the largest key cannot be a leaf node.
    • False, what if it’s only a root, it is also a leaf?