[Home]History of Heap

HomePage | Recent Changes | Preferences

Revision 9 . . October 26, 2001 3:25 am by (logged).157.137.xxx [Finished explaining heap-up and explained removal from the heap.]
Revision 8 . . October 26, 2001 3:11 am by DrBob [better way of fixing "\" problem]
  

Difference (from prior major revision) (no other diffs)

Changed: 4c4
than the value stored at either of its two children.
than the value stored at either of its two children. (This is called the "heap property".)

Changed: 27c27,37
the array; if the greatest value of the three nodes is not in the top node, exchange.
the array; if the greatest value of the three nodes is not in the top node, exchange it with
the top node. This puts the former top node at the top of a subtree which may contain nodes
greater than it is; so we must compare it with its new children and possibly repeat the
process.

It appears offhand to me that this should make this process take O(n lg n) time, but
all the references I can find say it's O(n), although I can't understand their proofs.
Once you have a heap, you can quickly find the node with the greatest value in it; it will be the node at the root of the tree. If you want to remove this node (as is necessary for a priority queue), in the array representation, you can swap that node's value with the value of the last node in the array (node 11 in the above example), shorten the array by 1 (removing that last node from the heap), and then restore the heap property, which still holds everywhere but at the top of the heap. The value at the top of the tree is now less than at least one of its children; swap it with the greater of its two children, and the heap property will be true at the top, but now possibly not where the top node was just swapped to; so you have to repeat the process until it is greater than either of its two children, which probably means until it reaches the bottom of the heap --- up to lg n swaps.


So removing the largest node from a heap takes O(lg n) steps.

HomePage | Recent Changes | Preferences
Search: