Ejemplo n.º 1
0
 def enqueue(self, item):
     BinHeap.insert(self.queue, item)
Ejemplo n.º 2
0
from pythonds.trees.binheap import BinHeap

bh = BinHeap()
bh.insert(5)
bh.insert(7)
bh.insert(3)
bh.insert(11)

print(bh.delMin())

print(bh.delMin())

print(bh.delMin())

print(bh.delMin())
Ejemplo n.º 3
0
'''
基本操作
BinaryHeap() 创建一个新的,空的二叉堆。
insert(k) 向堆添加一个新项。
findMin() 返回具有最小键值的项,并将项留在堆中。
delMin() 返回具有最小键值的项,从堆中删除该项。
如果堆是空的,isEmpty() 返回 true,否则返回 false。
size() 返回堆中的项数。
buildHeap(list) 从键列表构建一个新的堆。
'''

from pythonds.trees.binheap import BinHeap

bh = BinHeap()
bh.insert(5)
bh.insert(7)
bh.insert(3)
print(bh.delMin())
print(bh.heapList)


class BinHeap1:
    def __init__(self):
        self.headList = [0]
        self.currentSize = 0

    #新添加的项小于其父项,将项与其父项交换, 当前节点的父节点可以通过将当前节点的索引除以2来计算
    def percUp(self, i):
        while i // 2 > 0:
            if self.headList[i] < self.headList[i // 2]:
                tmp = self.headList[i // 2]
Ejemplo n.º 4
0
## Using PriorityQueue ##
#pq = PriorityQueue({1: "a", 2: "b", 3: "c"})
pq = PriorityQueue()
pq.put((2, 'code'))
pq.put((1, 'sleep'))
pq.put((3, 'eat'))
while not pq.empty():
	print(pq.get())

## Using Binary Heap to implement Priority queue ##
p1 = [(2, "code"), (1, "eat"), (3, "sleep")]
heapq.heapify(p1)
p2 = []
heapq.heappush(p2, (1, "code"))
heapq.heappush(p2, (2, "eat"))
print("p1", p1)
while p1:
	print(heapq.heappop(p1))
print("p2", p2)
while p2:
	print(heapq.heappop(p2))

## Using pythonds module ##
p3 = BinHeap()
p3.insert(1)
p3.insert(2)
p3.insert(4)
print("p3", p3)
print(p3.delMin())
Ejemplo n.º 5
0
from pythonds.trees.binheap import BinHeap

bh = BinHeap()
bh.insert(5)
bh.insert(55)
bh.insert(10)
bh.insert(2)
bh.insert(8)

print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())