How to build a Min-Max Heap in O(n) time complexity?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 07:15:22

问题


I found the topic of min-max heap on Wikipedia. I was wondering if there is any way of building this min-max heap in O(n).

I know you can do this with both min heap and max heap, but I'm not sure what would be the approach for this. Inserting an element takes O(log n) time complexity and I feel like this kind of tree can't be build more efficiently than O(n log n).


回答1:


Yes, it can. In your build-heap loop, you simply call TrickleDown, just like you would with a min heap or a max heap. That function will move the item accordingly, depending on whether it's on a min level or a max level.

See the original paper, Min-Max Heaps and Generalized Priority Queues for general info. The paper doesn't implement build-heap, but if you write your own that calls TrickleDown, it works as expected. That is:

for i = A.length/2 downto 0
    TrickleDown(i)

TrickleDown determines if i is on a min level or a max level, and calls the appropriate method, TrickleDownMin or TrickleDownMax.



来源:https://stackoverflow.com/questions/47076465/how-to-build-a-min-max-heap-in-on-time-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!