1

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).

Gaurang Tandon
  • 5,704
  • 9
  • 37
  • 73
Cherry
  • 51
  • 1
  • 10
  • That wikipedia article indicates that you can use Floyd's O(n) algorithm to build a min-max heap. There are also references which help explain why that algorithm is O(n). – rici Nov 02 '17 at 13:37
  • I really tried to understand that alogirthm, but as I just started studying algorithms it's quite hard for me to understand, that's why I was hoping to get some help here. – Cherry Nov 02 '17 at 13:38
  • 1
    The best way to understand simple algorithms is with pencil and paper. Try it out on some inputs and you will probably see how it works. (It's the same approach which is used to build the heap in the heapsort algorithm, which might be easier to work through.) – rici Nov 02 '17 at 13:45

1 Answers1

3

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.

Jim Mischel
  • 122,159
  • 16
  • 161
  • 305
  • what is the time complexity of TrickleDown(i) to determine where i move. – DHARMENDRA SINGH Feb 12 '19 at 05:50
  • @DHARMENDRASINGH `TrickleDown(i)` has worst-case time complexity of O(log n). But in the context of the build-heap operation, we know how the maximum number of calls to `TrickleDown` will be made, and what the complexity will be. See https://stackoverflow.com/q/49774237/56778 – Jim Mischel Feb 13 '19 at 05:20