优先级队列具有每个条目的优先级值和数据。
因此,当将新元素添加到队列中时,如果它的优先级值高于集合中已有的元素,则它会冒泡到图面。
当一个调用pop时,我们获取具有最高优先级的元素的数据。
在Javascript中,这种优先级队列的有效实现是什么?
创建一个名为PriorityQueue的新对象、创建两个方法是否有意义(推入和弹出),它使用两个参数(数据,优先级)?作为一个程序员,这对我来说很有意义,但是我不确定在底层使用哪种数据结构来允许对元素的排序进行操作。或者我们可以将所有元素都存储在一个数组中,然后每次遍历数组以获取具有最大优先级的元素?
有什么好办法可以做到这一点?
5条答案
按热度按时间7jmck4yq1#
Below is what I believe to be a truly efficient version of a
PriorityQueue
which uses an array-based binary heap (where the root is at index0
, and the children of a node at indexi
are at indices2i + 1
and2i + 2
, respectively).This implementation includes the classical priority queue methods like
push
,peek
,pop
, andsize
, as well as convenience methodsisEmpty
andreplace
(the latter being a more efficient substitute for apop
followed immediately by apush
). Values are stored not as[value, priority]
pairs, but simply asvalue
s; this allows for automatic prioritization of types that can be natively compared using the>
operator. A custom comparator function passed to thePriorityQueue
constructor can be used to emulate the behavior of pairwise semantics, however, as shown in the example below.Heap-based Implementation:
Example:
cgh8pdjw2#
您应该使用标准库,例如Closure库(
goog.structs.PriorityQueue
):https://google.github.io/closure-library/api/goog.structs.PriorityQueue.html
通过点击源代码,你会知道它实际上是链接到
goog.structs.Heap
,你可以跟随:https://github.com/google/closure-library/blob/master/closure/goog/structs/heap.js
4c8rllxm3#
我对现有优先级队列实现的效率并不满意,所以我决定自己创建一个:
https://github.com/luciopaiva/heapify
由于使用了类型化数组,这将比任何其他公知的实现运行得更快。
在客户端和服务器端都能工作,代码库具有100%的测试覆盖率,小库(~100 LoC)。而且,界面非常简单。下面是一些代码:
holgip5t4#
I provide here the implementation I use. I made the following decisions:
<
,>
, ...). This works fine for numbers, bigints, strings, and Date instances. In case the values are objects that would not order well like that, theirvalueOf
should be overridden to guarantee the desired ordering. Or, such objects should be provided as payload, and the object's property that really defines the order, should be given as the value (in first array position).heapq
module works and gives a "light" feeling to it: You work directly with your own array. Nonew
, no inheritance, just plain functions acting on your array.Here follows that collection of functions, with comments, and a simple demo at the end:
For a more realistic example, see the implementation of Dijkstra's shortest path algorithm .
Here is the same
MinHeap
collection, but minified, together with itsMaxHeap
mirror:odopli945#
从@gyre的回答中得到了一些灵感,用TypeScript写了一个简约的版本,大约缩小了550字节。
用法: