What is a Heap?

A heap (as used in heap sort) is a binary tree where each node has (at most) two child nodes.
4 8 10 3 6 9 7 2 1 5

The bottom row of the heap is always filled from left to right.
Every node forms a sub-heap -- all the values that descend from that node.
Since a heap is completely fixed, it can be mapped to a linear array

3 6 9 7 2 1 4 5 10 8
The children of a parent node are always at 2*index and 2*index+1 (or 2*index+1 and 2*index+2 if your arrays start from 0)
The last parent node is always exactly half way through the heap.

If each parent is equal to or greater than both it's children, then the heap is called "correct".
If one or more children are a greater than their parent, then the heap is called "incorrect".
A node without children is correct.
You can remove the last element on the bottom right of a correct heap, and you will still have a correct heap.
Every parent node in a correct heap is equal to or greater than all it's descendants (all values beneath it in the heap).
The top element is always the greatest element in a correct heap.

Heap Sort often adds these utility functions, presumably so the heap can be used as a database.
Here are general utility functions that operate on the heap
Theoretically, you could use Heapify to create a correct heap in O(N) time, then search the heap for values in O(log N) time.
I suppose there might be some reason to do this rather than using an associative array (a.k.a. hashing), but none come to mind.

^ UP ^    < Back to Heap Sort <