What is a heap?

A heap is a complete binary tree, each of whose nodes contains a key which is greater than or equal to the key in each of its children. Actually, this is technically a "maximum heap"; if we replace "greater than or equal to" with "less than or equal to", we get the definition of a "minimum heap".

Note that this use of the term heap has absolutely nothing to do with the other meaning of the word heap, which in that context was another term for "free store". Two words that have the same spelling or pronunciation but different meanings are called homonyms. Here are some other examples in which the sound is again the same, but at least the spelling is different: so and sew; do, dew, due; grate and great.

Thus we may say that a heap satisfies two properties:

  1. A "shape property" (that is, it's a complete binary tree)
  2. An "order property" (the value in a node is "optimal" with respect to the values in all nodes below it)

What are some uses for heaps?

In order to deal with this question we introduce a new way of representing binary trees.

Non-linked representation of binary trees

Study the binary tree shown below, and the array (or vector) that immediately follows it and contains the same values:

Note that although this binary tree happens to be a heap, it could be any kind of binary tree. That is, we could use this kind of representation for any of our binary trees; it's just that it turns out to be particularly convenient for heaps. You should make the following observations:

Now that we know what a heap is, and how we are going to represent it, it's time for the usual questions:

Though it seems natural to ask the above questions in the order given, it turns out to be convenient to answer them in the opposite order. These pictures illustrate the heap algorithms we need.