- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHeap.py
More file actions
Latest commit
88 lines (79 loc) · 2.15 KB
/
Copy pathHeap.py
File metadata and controls
88 lines (79 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# implement priority queue
# using heap to sort the priority
classNode(object):
def__init__(self,data=None,priority=None):
self.data=data
self.priority=priority
# implement the min heap
classMinHeap(object):
def__init__(self, key=None):
self.items= []
self._key=keyor (lambdax: x)
defsize(self):
returnlen(self.items)
defswap(self,a,b):
temp=self.items[a]
self.items[a] =self.items[b]
self.items[b] =temp
# inset an element into the list
definsert(self,num):
self.items.append(num)
n=len(self.items) -1
# siftup the nth element in the list
self.siftup(n)
returnself.items
# siftup the nth element
defsiftup(self,n):
i=n
# parent index
p= (n-1)/2
whilei>=0and (
self._key(self.items[p]) >self._key(self.items[i])):
temp=self.items[i]
self.items[i] =self.items[p]
self.items[p] =temp
i=p
p= (n-1)/2
returnself.items
# siftdown the element place on the first position in the heap
defsiftdown(self,n):
i=0
whileTrue:
left=2*i+1
ifleft>n:
break
lesser_child=left
right=2*i+2
ifright<=nand (
self._key(self.items[right]) <self._key(self.items[left])):
lesser_child=right
ifself._key(self.items[i]) <=self._key(self.items[lesser_child]):
break
self.swap(i, lesser_child)
i=lesser_child
returnself.items
# pop the heap, return the root
defpop(self):
minNode=self.items[0]
last=self.items.pop()
ifself.items:
self.items[0] =last
# place the last element on the root and then siftdown
self.siftdown(len(self.items)-1)
returnminNode
classMaxHeap(MinHeap):
def__init__(self, key=None):
super(MaxHeap, self).__init__()
self._key= (lambdax: -key(x)) ifkeyelse (lambdax: -x)
defmain():
minheap=MinHeap()
printminheap.insert(2)
printminheap.insert(1)
printminheap.insert(3)
printminheap.insert(6)
printminheap.insert(8)
printminheap.insert(4)
printminheap.pop()
printminheap.items
if__name__=="__main__":
main()