问题
In the section that explains Dijkstra's Algorithm in the book Introduction to Algorithms by Cormen et. al., while analysing the complexity of the algorithm, they say
If the graph is sufficiently sparse ... we can improve the algorithm by implementing the min priority queue with a binary min heap
So I was wondering, what is the need for such a statement? Isn't it always wiser to just use heaps for priority queues?
回答1:
There are many different ways to implement a priority queue. A binary min heap is useful because it performs reasonably well and is easy to implement. But a pairing heap is pretty easy to implement, too, and it has better performance for some operations. In particular, it does a decrease key operation much more quickly than a binary heap does.
Or you could go with a skip list priority queue. A skip list has some nice properties that make it attractive in some priority queue applications. In particular, it's easier to make a concurrent skip list than a concurrent heap.
So, no, it's not always wiser to use heaps for priority queues. It's almost certainly wiser to use a heap than a sorted list, but there are times when something else is more appropriate than a heap.
回答2:
See https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
It says:
- Dijkstra's original algorithm does not use a min-priority queue and runs in O(|V|^2).
So the statement in the book is just saying that the original algorithm can be optimized.
- The implementation based on a min-priority queue implemented by a Fibonacci heap and running in O(|E|+|V|log|V|) (where |E| is the number of edges) is due to (Fredman & Tarjan 1984).
Binary heap is only one type of heap. There are other types which fit specific scenes better.
来源:https://stackoverflow.com/questions/19025317/when-is-it-a-bad-idea-to-use-a-heap-for-a-priority-queue