What happens if we iterates build-max- heap in Top Down Manner

483 views Asked by At

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)
}
2

There are 2 answers

3
Jim Mischel On BEST ANSWER

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:

for (i=1 to [A.length]/2)

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:

        4
      3   2
    1

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:

        2
      1   4
    3

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.

0
user1095108 On

a max or min heap is an implementation of a nested max or min function, e.g. max(max(max(a, b), max(c, d)), ...), it is a kind of an expression tree for min() or max() of all array elements, that is, you are implementing max(a, b, c, ...) or min(a, b, c, ...). To yield the correct result you need to gather the min or max elements to compare. To do that you need to do a broad comparison of the bottom elements, then going up, the number of elements you need to compare is divided by 2 per level (one half are eliminated per level). Going from top to bottom will not yield the correct result; you are implementing the wrong expression.