-
Notifications
You must be signed in to change notification settings - Fork 3
/
minHeap.py
57 lines (46 loc) · 1.24 KB
/
minHeap.py
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
class min_heap:
def __init__(self, A=[]):
self.heapify(A)
def shift_up(self, i):
while i // 2 > 0:
if self.h[i] < self.h[i // 2]:
self.h[i], self.h[i//2] = self.h[i//2], self.h[i]
i = i // 2
def shift_down(self, i):
while (i * 2) <= len(self.h)-1:
mc = self.minChild(i)
if self.h[i] > self.h[mc]:
self.h[i], self.h[mc] = self.h[mc], self.h[i]
i = mc
def minChild(self, i):
if i * 2 + 1 > len(self.h)-1:
return i * 2
if self.h[i*2] < self.h[i*2+1]:
return i * 2
else:
return i * 2 + 1
def heappop(self):
if len(self.h) == 1:
return None
ans = self.h[1]
self.h[1] = self.h[len(self.h)-1]
self.h.pop()
self.shift_down(1)
return ans
def heappush(self, a):
self.h.append(a)
self.shift_up(len(self.h)-1)
def heapify(self, A):
self.h = [0] + A
i = 1
while (i < len(self.h)):
self.shift_down(i)
i = i + 1
# 使用:
h = min_heap([5, 6, 2, 3])
h.heappush(1)
h.heappop() # 1
h.heappop() # 2
h.heappush(1)
h.heappop() # 1
h.heappop() # 3