Heaps and
Heapsort


Heaps and Heapsort:

Here are details about heaps and the heapsort algorithm.

  1. A heap is an object with the properties:

  2. Restoring the heap property, if violated at node i:
  3. Building a heap, starting with array A[1], ..., A[n] and heapsize(A) == n.
  4. Heapsort algorithm, starting with array A[1], ..., A[n]

Use of a heap as a priority queue:

  1. Start with an array A holding n priority numbers in locations A[1], ..., A[n].
  2. Use BuildMaxHeap(A) to turn A into a heap.
  3. Repeatedly remove the largest remaining element from A, using the following, which is about the same as one step of the heapsort algorithm:
  4. Another useful algorithm lets us increase a value in the array and restore the heap property:
  5. Finally, we can insert a new element into the array:

Examples: Here are four examples using diagrams of the heap at each stage:


Revision date: 2005-04-26. (Please use ISO 8601, the International Standard.)
Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.