In this exercise, I am trying to create a Max Heap from an array with six elements. To achieve this, I must compare each child node to its parent node and swap if needed.
I start from the 3rd index and compare it to the parent node (index 1). If the child is greater than the parent node, I swap them. I then go to the 2nd index and compare it to the parent node. Again, if the child is greater than the parent node, I swap them. Finally, I go to the 1st index and compare it to the child node. I again swap them if the child is greater.
Now, I have created a Max Heap. But why do I have to exchange A[1]
with A[6]
then A[1]
with A[5]
? Doing this results in a Min Heap, not a Max Heap. What does Heapify mean in this context?
Thanks for any help!
Heapify is a process of creating a heap from an array. In order to create a Max Heap from an array, you need to perform a series of comparisons and swaps between parent and child nodes. After this process is complete, you should have a valid Max Heap.
In your specific case, it seems like you are trying to create a Max Heap from an array with six elements. You start by comparing the child nodes to their parent node and swapping if needed. However, you mention that you exchange A[1]
with A[6]
and then A[1]
with A[5]
. This would result in a Min Heap, not a Max Heap.
In order to create a Max Heap, you should only perform the comparisons and swaps between parent and child nodes. You do not need to exchange elements at the beginning or end of the array. Once the Heapify process is complete, you should have a valid Max Heap.