what are the disadvantages if we construct build heap in top down manner with brief time complexity calculation.in brief using first buid-max-heap heap algorithm than commonly used second algorithm
Build-max-heap(A)
{
A.heap-size=A.length
for(i=1 to [A.lenth]/2)
max-heapify(A,i)
}
Build-max-heap(A)
{
A.heap-size=A.length
for(i=[A.lenth]/2 downto 1)
max-heapify(A,i)
}
As written, your first example won't do anything because
i
is less than[A.length/2]
. I suspect you meant your first example to be:Assuming that's what you meant, doing the min-heapify from the top, down will not result in a valid heap. Consider the original array
[4,3,2,1]
, which represents this tree:On the first iteration, you want to move 4, down. So you swap it with the smallest child and get the array
[2,3,4,1]
.Next, you want to filter 3. So you swap it with its smallest child and get
[2,1,4,3]
. You're done now, and your "heap" looks like this:Which is not a valid heap.
When you go from the middle, up, then the smallest item can filter its way to the top. But when you go from the top down, it's possible for the smallest item never to reach the top.