Binary heap

This is an old revision of this page, as edited by Dysprosia (talk | contribs) at 07:29, 27 June 2004 (first pass at cleaning this up). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Binary heaps are a particular kind of heap data structure such that each node only has two children, and the heap property is placed upon elements in the heap, such that internal nodes contain data that is either larger or smaller than elements in its children.

Min-heaps and max-heaps

Heaps can be organized so that the largest element in the heap is at the root of the tree always, or that the smallest element of the heap is at the root. These heaps are termed max-heaps and min-heaps respectively. Conventionally, max-heaps are used, since they are readily applicable for use in priority queues.

        1               11
      /   \           /    \
     2     3         9     10
    / \   / \       / \    / \
   4   5  6  7     5   6  7   8
  / \ / \         / \ / \
 8  9 10 11      1  2 3  4 

Binary heaps are also commonly represented by arrays of values. For example, the root of the tree could be item 0 in the array, and the children of item n are the items at 2n+1 and 2n+2; so item 0's children are items 1 and 2, 1's children are items 3 and 4, etc. This allows you to regard any 1-based array as a possibly-screwed-up heap.

The fact that we retrieving the maximum/minimum element from a heap is basis for the heapsort algorithm. Also note that the ordering of siblings in a heap is not specified by the heap property, so the two children of a parent can be interchanged.

Heap maintenance

If we have a heap, and we add an element, we can perform an operation known as up-heap, bubble-up, or sift-up in order to restore the heap property. We can do this in O(log n) time, using a binary heap, by adding the element on the bottom level of the heap regardless, then considering the added element and it's parent and swapping the element and its parent if need be until we are assured the heap property remains. We do this at maximum for each level in the tree - the height of the tree, which is O(log n).