How to preserve the order of elements of the same priority in a priority queue implemented as binary heap?

后端 未结 3 1401
夕颜
夕颜 2021-01-04 00:19

I have created a binary heap, which represents a priority queue. It\'s just classical well known algorithm. This heap schedules a chronological sequence of different events

3条回答
  •  长情又很酷
    2021-01-04 00:55

    As far as I know, heaps are never built to preserve order (which is why "heap sort" is notable for not being a stable sort).

    I understand that what you are asking is whether a small algorithmic trick might be able to change this (that is not the good old reliable "timestamp" solution). I don't think it's possible.

    What I would have suggested is some version of this:

    • keep the same "insert";

    • modify "remove" so that it ensures a certain order on elements of a given priority.

    To do this, in heap-down, instead of swapping elements down until the order is preserved: swap an element down until it as the end of an arborescence of elements of the same value, always choosing to go to the right when you can.

    Unfortunately the problem with this is that you don't know where insert will add an element of a given priority: it could end up anywhere in the tree. Changing this would be, I believe, more than just a tweak to the structure.

提交回复
热议问题