java PriorityQueue類在Java1.5中引入。PriorityQueue是基於優先堆的一個無界隊列,這個優先隊列中的元素可以默認自然排序或者通過提供的Comparator(比較器)在隊列實例化的時排序。要求使用Java Comparable和Comparator接口給對象排序,並且在排序時會按照優先級處理其中的元素
python 優先級隊列
這裏按"值越大優先級越高"的順序.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#coding=utf-8 from heapq import heappush, heappop class PriorityQueue: def __init__( self ): self ._queue = [] def put( self , item, priority): heappush( self ._queue, ( - priority, item)) def get( self ): return heappop( self ._queue)[ - 1 ] q = PriorityQueue() q.put( 'world' , 1 ) q.put( 'hello' , 2 ) print q.get() print q.get() |
使用heapq模塊來實現
下面的類利用 heapq 模塊實現了一個簡單的優先級隊列:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import heapq class PriorityQueue: def __init__( self ): self ._queue = [] self ._index = 0 def push( self , item, priority): heapq.heappush( self ._queue, ( - priority, self ._index, item)) self ._index + = 1 def pop( self ): return heapq.heappop( self ._queue)[ - 1 ] |
下面是它的使用方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
>>> class Item: ... def __init__( self , name): ... self .name = name ... def __repr__( self ): ... return 'Item({!r})' . format ( self .name) ... >>> q = PriorityQueue() >>> q.push(Item( 'foo' ), 1 ) >>> q.push(Item( 'bar' ), 5 ) >>> q.push(Item( 'spam' ), 4 ) >>> q.push(Item( 'grok' ), 1 ) >>> q.pop() Item( 'bar' ) >>> q.pop() Item( 'spam' ) >>> q.pop() Item( 'foo' ) >>> q.pop() Item( 'grok' ) >>> |