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:


Created By Dr. Neal Wager : The University of Texas at San Antonio