Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ( the sort key is time ).

It supports 2 operation: Insert and Remove. Each node's key of the heap is greater than or equal to each of its children. However, adding events with the same key doesn't preserve the order they were added, because each time after Remove or Insert were called, the heap-up and the heap-down procedures break the order.

My question is: what should be changed in a classical algorithm to preserve the order of the nodes with the same priority?

like image 776
psihodelia Avatar asked Aug 02 '11 09:08

psihodelia


1 Answers

One solution is to add time of insertion attribute to the inserted element. That may be just a simple counter incremented each time a new element is inserted into the heap. Then when two elements are equal by priority, compare the time of insertion.

like image 63
Juraj Blaho Avatar answered Sep 23 '22 10:09

Juraj Blaho