42B. Representing a Heap as an Array

The rigid structural requirement of a heap allows us to store a heap in an array. Number the nodes from 0 by levels, starting at the root and working left-to-right across each level. A node's number is called its index. The following shows indices in a small heap.

The idea is to store the node with index i of a heap at index i in an array. That allows us to move up and down in the heap easily, using the following functions.

  //===================================================
  //                leftchild
  //===================================================
  // leftchild(i) is the index of the left child of the
  // node with index i, if that node exists.
  //===================================================

  int leftchild(const int i)
  {
    return 2*i + 1;
  }

  //===================================================
  //                rightchild
  //===================================================
  // rightchild(i) is the index of the right child of
  // the node with index i, if that node exists.
  //===================================================

  int rightchild(const int i)
  {
    return 2*i + 2;
  }

  //===================================================
  //                parent
  //===================================================
  // parent(i) is the index of the parent of the node
  // with index i, provided i > 0.
  //===================================================

  int parent(const int i)
  {
    return (i-1)/2;
  }