1

I wan't to make a binary max heap through a given array. I can implement it in two ways:
1.Make a heap of the whole array and start heapifying through leaf nodes to the top.
2.Insert an element one-by-one into the heap from the array and heapifying simultaneously.

Both these methods give me a max heap, but are different from each other. So which method is the correct one?

Community
  • 1
  • 1

2 Answers2

1

You can implement the heap in either way and both are correct as they obey the basic rule of heap ordering that parent key has to be grater than either of child node. Though they might result in different heaps.

Method-1- Make a heap of the whole array and start heapifying through leaf nodes to the top. By this method the number of compares to construct the heap is O(N) i.e it takes linear number of compares and thus takes linear time.

Method-2- Insert an element one-by-one into the heap from the array and heapifying simultaneously. Inserting an element into an ordered heap takes logN compares on an average. So inserting N items and heap ordering simultaneously takes log1 + 2log2 +3log3 + ... + NlogN ~ NlogN compares and thus linearithmic time.

Thus method one is preferable as it takes fewer number of compares and thus lesser time.

Novneet Nov
  • 592
  • 1
  • 7
  • 22
0

Look both are different:
1. When you are inserting one by one : Basically you are inserting in Binary tree which is already a heap and call heapify
2. When you are inserting everything in an array at once and then making it heap altogether then you are not using heapify (BuildHeap function). Because that is not already a heap.

Heapify is used when you are inserting in an array which is already a heap

Read this.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
insanely_sin
  • 986
  • 1
  • 14
  • 22
  • No, this is not what I want. If I had enough reputation, I would have voted down this answer. –  Jun 22 '14 at 09:48