killerhunterman
killerhunterman

Reputation: 11

Max-heap representation of an array

As a homework problem, I have to draw out the max heap from an array. The question reads:

Please draw out the max-heap stored in the following array (heapsize is 6) A[] = {15,10,8,5,2,7,20,30}

So, when I attempted this question, I just did it the old fashioned way, and did not take into account that the heapSize is less than the array size.

The max heap I got was: {30,20,15,10,2,7,8,5}

My question is: Is this correct? Also, now that the heapSize is lesser than the array size, how does this affect the max heap produced? Should I only show the max heap array till the 6th element or should I modify my max heap?

Thanks!

Upvotes: 1

Views: 903

Answers (1)

janos
janos

Reputation: 124646

I think you misunderstood the exercise.

If we take the exercise literally, and "draw out" the max heap of size 6 from the given array, we get a tree like this:

      15
   10    8
  5  2  7 20
30

You can see that the first 6 elements of the array are in heap order.

This also looks suspiciously like the intermediary state of a heap sort: the largest value 30 is the last element, followed by the second largest 20. If we follow the heap sort algorithm, swapping the current max heap element 15 with the last element 7, and so on, the array will end up with values sorted in increasing order.

I don't what the exercise meant by "drawing out" the max heap, but I doubt it meant that to heapify the array, which is what you did.

Upvotes: 1

Related Questions