An array of real numbers, , is called a heap if for , where is the quotient of integer divided by 2 (e.g., ). A heap can be treated as a binary tree such that is the root node and is the parent node of . Answer the following questions.
(1) Explain whether array is a heap or not.
(2) Show that if is a heap, is also a heap for any .
(3) Suppose that is a heap but is not. Describe a procedure that exchanges elements in to make it a heap in worst-case time.
(4) Suppose that is a heap. Prove that is maximum among all elements in . Suppose that after replacing with , is not a heap. Describe a procedure that exchanges elements in to make it a heap in worst-case time.
(5) Describe an algorithm that exchanges elements in to make it a heap in worst-case time.
(6) Using the procedures defined above, describe an algorithm that sorts array in worst-case time.
Statement: If is a heap, then is also a heap for any .
Proof:
Let be a heap, meaning for all . Consider any . Since the heap property holds for all elements in , it will also hold for all elements in because the parent-child relationships in the heap are preserved up to index . Therefore, is also a heap.
Suppose is a heap, but after inserting an element at position , the array is not a heap. The violation of the heap property could only occur if the newly inserted element at position is greater than its parent. To fix this, we perform the heapify-up operation.
Heapify-up Procedure:
Let .
While and :
Swap and .
Set .
Time Complexity: The worst-case time complexity of this procedure is , as we may need to traverse up the height of the heap, which is logarithmic in terms of the number of elements.
Proof that is the maximum element in :
By the definition of a max-heap, the root node (i.e., ) must be greater than or equal to all its children. By induction, it can be proven that is greater than or equal to all elements in the heap. Hence, is the maximum element.
Heapify-down Procedure:
After replacing with , if is not a heap, we need to restore the heap property by performing the heapify-down operation.
Let .
While (i.e., while has at least one child):
Let (left child).
If and , set (right child is larger).
If , break the loop.
Swap and .
Set .
Time Complexity: The worst-case time complexity of this procedure is , as we may need to traverse down the height of the heap.