1

Suppose we have a min heap with some elements which satisfy the heap property. What happens if I change the algorithm from min heap to max heap without rearrange the internal array?

That is, if I keep the array unchanged, what happens when I append an element to the internal array?

2 Answers 2

8

Consider the following example from Wikipedia: enter image description here

The array representation of this would look like this:

[1, 2, 3, 17, 19, 36, 7, 25, 100]

Now we "change" the heap from min to max, but without rearranging the elements and insert a new element "25". The array position would be 9 so the parent node is "19" at position 4.

After inserting we must repeatedly compare the new item with its parent to ensure heap property (now max-heap => parent must be greater than child). Thus we must swap "25" with "19", "2" and "1" until it is the root node.

Now the max-heap property holds for the root node (its children are indeed smaller), but not for the other nodes, e.g. "3" is still the parent of "7" and violates the max-heap condition.

To conclude this: Doing what you describe does not change the min-heap to a max-heap.

Sign up to request clarification or add additional context in comments.

Comments

6

You would just screw the heap.

You have to re-heapify (this can be done in time O(N)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.