CS35: Data Structures and Algorithms

Complete Binary Heap Notes
We can represent a Heap using a complete binary tree and pack the entire tree into an array data structure. Below is a sketch of the primary member variables, public ADT methods, and private helper methods.
/* member variables */
int size
int capacity
Pair<P,V>* items /* array of priority/value pairs */

/* constructor */
BinaryHeap()
  capacity = 10
  size = 0
  items = new pair<P,V>[capacity]

/* TODO: destructor */
The primary public ADT methods are insert and removeMax.
void insert(prio, value):
   Pair<P,V> item(prio, value);
   if size == capacity:
     expandCapacity() /* Same as ArrayList */
   items[size] = item
   size++
   bubbleUp(size-1)
value removeMax():
   root = 0
   val = items[root].second
   /* copy last item to root */
   items[root] = items[size-1]
   size--
   bubbleDown(root)
   return val
The complete binary heap and array representation make use of several helper functions sketched below

void expandCapacity():
  /* make new array when old one is full, doubling capacity
     see ArrayList implementation */


/* Note that getLeft and getRight do not check if returned index
   is within range of number of elements in heap. */

void getLeft(i):
  /* get index of left child of node at index i in array */
  return 2*i+1

void getRight(i):
  /* get index of right child of node at index i in array */
  return 2*i+2

void getParent(i):
  /* get index of parent of node at index i in array */
  return (i-1)/2

void bubbleUp(current):
  if current is root:
     return
  if priority of current > priority of getParent(current):
     swap(current, getParent(current))
     bubbleUp(getParent(current))

void bubbleDown(current):

   if current is leaf:
     /*TODO: how do you determine if an index is a leaf? */
     return

   /* TODO: find maxChild. Handle case of only one child */
   maxChild = child with higher priority
   if priority of current < priority of maxChild:
     swap(current, maxChild)
     bubbleDown(maxChild)

Building a heap from scratch

void Heapify(A, n):
  for (i = n-1; i>=0; i--)
    bubbleDown(A,i)