How do an unsorted list, a sorted list and a heap compare as implementations of an adaptable priority queue with location-aware entries?
The lists each make some operations $O(1)$ and others $O(n)$; the heap makes everything at most $O(\log n)$. Location awareness is what brings remove down to $O(1)$ / $O(1)$ / $O(\log n)$ and the heap's replaceKey to $O(\log n)$.
| Method | Unsorted list | Sorted list | Heap |
|---|---|---|---|
size, isEmpty |
$O(1)$ | $O(1)$ | $O(1)$ |
insert |
$O(1)$ | $O(n)$ | $O(\log n)$ |
min |
$O(n)$ | $O(1)$ | $O(1)$ |
removeMin |
$O(n)$ | $O(1)$ | $O(\log n)$ |
remove |
$O(1)$ | $O(1)$ | $O(\log n)$ |
replaceKey |
$O(1)$ | $O(n)$ | $O(\log n)$ |
replaceValue |
$O(1)$ | $O(1)$ | $O(1)$ |
Each row follows from what the structure must maintain:
removeis constant time in both lists because the entry knows its node and unlinking costs $O(1)$; the heap must repair order after moving the last entry in, which costs $O(\log n)$.replaceKeyis free in the unsorted list (there is no order to keep), but $O(n)$ in the sorted list, because the entry has to be relocated to its new place in the order. The heap does it with one up- or downheap.replaceValueis $O(1)$ everywhere: values never affect position.
Without location-aware entries, remove and replaceKey would have to search for the entry first and would be $O(n)$ in all three implementations.
Which one to choose depends on the operation mix. The heap is the all-rounder with no linear operation, which is why it is the standard implementation; a list only wins when one kind of operation strongly dominates.
Go deeper:
Priority queue: summary of running times — the same comparison extended to binomial, Fibonacci and pairing heaps.