Heapsort: 1 Heap
Heapsort: 1 Heap
Eduar A. Yanez
July 9, 2019
1 Heap
The (binary) heap data structure is an array object that we can view as a nearly
complete binary tree, as shown in Figure 1. Each node of the tree corresponds to
an element of the array. The tree is completely filled on all levels except possibly
the lowest, which is filled from the left up to a point. An array A that represents a
heap is an object with two attributes: A. length, which (as usual) gives the number
of elements in the array, and A. heap-size, which represents how many elements in
the heap are stored within array A. That is, although A[1 . . A. length] may contain
numbers, only the elements of in 1 . . A. heap-size, where 0 ≤ A. heap-size ≤
A. length, are valid elements of the heap. The root of the tree is A. 1, and given the
index i of a node, we can easily compute the indices of its parent, left child, and
right child:
1
16
2 3
14 10
4 5 6 7
8 7 9 8
8 9
2 4
Figure 1: A max-heap viewed as a binary tree. The number within the circle at
each node in the tree is the value stored at the node. The number above a node is
the corresponding index in the array.
1
1 2 3 4 5 6 7 8 9
16 14 10 8 7 9 8 2 4
Figure 2: Above and below the array are lines showing parent-child relationships:
parents are always to the left of their children.
Parent(i)
1 return i/2
Left(i)
1 return 2i
Right(i)
1 return 2i + 1
Build-Max-Heap(A)
1 A. heap-size = A.length
2 for i = A. length/2 downto 1
3 Max-Heapify(A, i)
2
Heapsort(A)
1 Build-Max-Heap(A)
2 for i = A. length downto 2
3 exchange A[1] with A[i]
4 A. heap-size = A. heap-size − 1
5 Max-Heapify(A, 1)