# Python实现优先队列

Python有队列类Queue，为啥就不提供个PriorityQueue类呢？

def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.

If x is already in a, insert it to the right of the rightmost x.

Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""

if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)

insort = insort_right 

#-*-coding:utf-8-*-
"""
class PriorityQueue:
"""

class PriorityQueue:
def __init__(self):
self.queue = []
self.length = 0
self.queue.insert(0, self.length)

#队列中元素的个数
def count(self):
return self.length

#判断队列是否为空
def empty(self):
if self.count() == 0:
return True
else :
return False

#取队列首元素，但是此时没有删除该元素
def top(self):
return self.queue[1]

#删除队首元素
def pop(self):
bEmpty = self.empty()
if bEmpty == False:
self.queue[1] = self.queue[self.length]
self.length -= 1

#插入一个元素
def push(self,item):
self.length += 1
self.queue.insert(self.length, item)

#插入元素后对堆进行调整，使其满足最大顶堆的性质
i = self.length
while i >= 2 and self.queue[i][1] > self.queue[i/2][1]:
self.queue[i] , self.queue[i/2] = self.queue[i/2] , self.queue[i]
i = i / 2

#堆的调整函数
root = 1
j = root << 1
temp = self.queue[root]
while j <= self.length:
if j < self.length and self.queue[j][1] < self.queue[j+1][1]:
j += 1
if self.queue[j] <= temp:
break
self.queue[j],self.queue[root] = self.queue[root],self.queue[j]
root = j
j = j << 1

self.queue[root] = temp

if __name__ == '__main__':
pq = PriorityQueue()
pq.push(15)
pq.push(8)
pq.push(9)
pq.push(3)
pq.push(7)
pq.push(6)
print pq.queue
while pq.empty() == False:
print "Value = ",pq.top()
print pq.queue,pq.length
pq.pop()

• 本文已收录于以下专栏：

举报原因： 您举报文章：Python实现优先队列 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)