In order to make a binary tree as a heap, we design an algorithm to adjust a binary tree to be a max heap. The function adjust(the-array, the-root, the-size) is used to adjust the array representation of a max heap, which is a complete binary tree. It considers the root of a subtree and assumes that its left subtree is a max heap, and its right subtree is also a max heap. The goal is to make the subtree a max heap.
int get_max_child(int a[], int parent, int n)
{
// return the index of max child
int child = parent * 2;
if (child > n)
return -1; // no child exists
if (child < n && a[child] < a[child + 1])
return child + 1;
else
return child;
}
void adjust(int a[], int root, int n)
{
int parent = root;
int child = get_max_child(a, parent, n);
while (child != -1 && a[parent] < a[child])
{
swap(a[parent], a[child]);
parent = child;
child = get_max_child(a, parent, n);
}
}
void heapSort(int a[], int n)
{
// sort a[1].. a[n]
/* make initial max heap */
for (int i = n; i >= 1; i--)
{
adjust(a, i, n);
}
}
According to the above introduction to HeapSort algorithm: [5 marks] Fill in the code in line 7 and line 15.
(i) [5 marks] Analyze the time complexity of the first step of HeapSort, making initial max heap (lines 27-30), using the following approach. In this problem, assume n is the number of nodes in the binary tree. It is easy to prove that the time cost of adjust(a, i, n) is the height of the subtree rooted at node i. If i is a leaf node, the time cost of adjust(a, i, n) is merely 1. If i is the parent of a leaf node, the time cost of adjust(a, i, n) is 2. The number of such nodes is 2^(h-1), where h is the height of the binary tree. If i is in the j-th bottom layer, the time cost of adjust(a, i, n) is j. The time cost of adjust(a, root, n) is k, where k is the height of the binary tree. There is only one root. Therefore, the total time cost of adjusting all n nodes is:
T(n) = 1^2 + 2^2 + ... + k^2
With the help of some math skills such as calculating 2T(n), you could derive a more concise expression of T(n), and then give its time complexity using big-O notation.
(b) The following algorithm shows another way of making the initial max heap.
(ii) [5 marks] Input an array = [7, 3, 8, 6, 2, 9] and n = 6 to heapSort2, i.e. a[1] = 7 and a[n] = 9. Draw the contents of the array after each UpwardAdjust(a, i) operation.
void UpwardAdjust(int a[], int i)
{
/* Initially, a[1] to a[i-1] form a max heap. This adjust algorithm will iteratively move a[i] upward until a[1] to a[i] become a max heap. */
int child = i;
int parent = child / 2;
while (parent >= 1 && a[child] > a[parent])
{
swap(a[child], a[parent]);
child = parent;
parent = child / 2;
}
}
void heapSort2(int a[], int n)
{
// sort a[1].. a[n]
/* make initial max heap */
for (int i = 2; i <= n; i++)
{
UpwardAdjust(a, i);
}
}