开发者

Building a valid heap

I just need some verification on whether or not I'm doing this correctly. I checked the wiki for a heapsort, but it seems in the animation to build the heap it inserts the numbers into the nodes and orders it as it goes.

The question asks to "Draw a valid heap with these elements.. {7, 12, 1, 3, 22, 5, 11} as a tree"

I've tried it on a few examples, and it seems I should layout the nodes first then reorder the nodes instead of ordering it as I go. Is the way I'm doing it correct?

For example, putting elements into the nodes

       7

   12     1

 3  22   5  11

Ordering begins here: swap 1 and 7

       7

   12     开发者_JAVA技巧1

 3  22   5  11

Swap 3 and 12

       1

   12     7

 3  22   5  11

Swap 5 and 7

       1

   3       7

 12  22   5  11

done.

       1

   3       5

 12  22   7  11

Actually that's not right.

The answer given is

       1

   7       3

 12  22   5  11

If I begin to re-order the heap from the left side first (beginning with 3) then I get the right answer.


Actually, the heap data structure as only one property, which can be defined as follows: "In a heap T, for every node v other than the root, the key stored at v is greater than or equal to the key stored at v's parent."

So there are many right representations of the heap based on elements (7, 12, 1, 3, 22, 5, 11). With these elements I applied an "insert-and-sort" algorithm and the result gives yet another version:

        1
   3         5
12   22   7    11
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜