Heaps and The Heapsort
Heaps and The Heapsort
Heaps and The Heapsort
Heaps and priority queues Heap structure and position numbering Heap structure property Heap ordering property Removal of top priority node Inserting a new node into the heap The heap sort Source code for heap sort program
Heap semantics
The usage of the term heap to describe a tree sorted from bottom to top is unrelated to usage of the same term for the pool of memory available for dynamic allocation, i.e. using malloc(). It does relate to the winner of a competive process, e.g. a football league, as being "at the top of the heap".
A heap can be visualised as a binary tree in which every layer is filled from the left. For every layer to be full, the tree would have to have a size exactly equal to 2n1, e.g. a value for size in the series 1, 3, 7, 15, 31, 63, 127, 255 etc. So to be practical enough to allow for any particular size, a heap has every layer filled except for the bottom layer which is filled from the left.
Because this numbering system makes it very easy to move between nodes and their children or parents, a heap is commonly implemented as an array with element 0 unused.
For a heap based on the above structure to be maintained, every layer must be complete except the bottom layer, which must be filled from the left and items must be removed from the right.
In order to insert items elsewhere and remove items from the top, localised rearrangements along single branches will made to restore this structure.
Removal of the top node creates a hole at the top which is "bubbled" downwards by moving values below it upwards, until the hole is in a position where it can be replaced with the rightmost node from the bottom layer. This process restores the heap ordering property.
Values above a hole within the structure are bubbled down into the hole, so the hole "bubbles up" to the position where the hole can receive the value to be inserted while maintaining the heap ordering property.
Source code 1
Source code 2
Source code 3
Source code 4
Source code 5
Source code 6
Source code 7