Similar to Binary Search Trees, a heap is a collections of nodes, of which only have, at most, two children. Typically there is an ordering scheme which provides a great deal of functionality. The code in this post is for a "max heap". This means that any time a node is inserted or removed, the heap will adjust itself so that the largest value will always be the "root". (A min heap is the exact opposite of this).

A textbook definition if you please, Mr. Wiki:

Quote

A binary heap is a heap data structure created using a binary tree. It can be seen as a binary tree with two additional constraints:
* The shape property: the tree is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to right.
* The heap property: each node is greater than or equal to each of its children according to some comparison predicate which is fixed for the entire data structure.

In layman's terms, we are going to ensure that the heap is never unbalanced (we'll accomplish this by using an array backed heap and always inserting at the end [first open space] of that array) and shifting the heap to ensure that every node is less then its parent and the root is the largest.

An Array Backed Heap

Unlike the post on BSTs, each node does not contain references/handles to its children. We use a simple mathematical relationship to obtain the children for a node at a given index, which is as follows:

a[i]'s children:
a[2i+1] left
a[2i+2] right

a[i]'s parent:
a[floor((i+1/2))]

Which looks like this:

NOTE: This is for an array implementation that starts at zero. You can start at one and just discard/ignore the first index, but the formulas will be slightly different.

Heap Order Property

As already mentioned, the example presented is a max heap. We'll keep track of how much space we have (the size of the array) in addition to the actual number of elements we have in the heap (the heap size). To maintain the max heap property, this is the pseudo code of insertion and removal:

Insertion
Add node to the first available "spot". This is the "end" of the heap.
Percolate up

If the node above is less then the node we just inserted, swap places.
Move up a level
Repeat until you at the top or the node above is greater [heap condition is satisfied].

Visually:

Inserting 4, 10, 43, 100, 15

Removal

Removal always "pops" the root off, aka the largest item.
Swap the largest item with the last item in the heap (heapsize-1 index).
Delete the heapsize-1 node and set its pointer to NULL
Now that the lowest item is on top:
Percolate down

Check to see if the node has any children
if so, check to see what is larger
if the child is larger, swap and continue percolating down until there are no more children or the heap condition is satisfied