-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.py
More file actions
66 lines (53 loc) · 1.99 KB
/
Copy pathheap.py
File metadata and controls
66 lines (53 loc) · 1.99 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
import numpy as np
from node import Node
class Heap:
def __init__(self, maxSize):
self.items = np.empty(maxSize, dtype = Node)
self.currentItemCount = 0
def add(self, item):
item.heapIndex = self.currentItemCount
self.items[self.currentItemCount] = item
self.sortUp(item)
self.currentItemCount += 1
def removeFirst(self):
firstItem = self.items[0]
self.currentItemCount -= 1
self.items[0] = self.items[self.currentItemCount]
self.items[0].heapIndex = 0
self.sortDown(self.items[0])
return firstItem
def updateItem(self, item):
self.sortUp(item)
def contains(self, item):
return self.items[item.heapIndex] == item
def sortUp(self, item):
parentIndex = int((item.heapIndex-1)/2)
while True:
parentItem = self.items[parentIndex]
if item.compareTo(parentItem) > 0:
self.swap(item, parentItem)
else:
break
parentIndex = int((item.heapIndex-1)/2)
def sortDown(self, item):
while True:
childIndexLeft = item.heapIndex * 2 + 1
childIndexRight = item.heapIndex * 2 + 2
swapIndex = 0
if childIndexLeft < self.currentItemCount:
swapIndex = childIndexLeft
if childIndexRight < self.currentItemCount:
if self.items[childIndexLeft].compareTo(self.items[childIndexRight]) < 0:
swapIndex = childIndexRight
if item.compareTo(self.items[swapIndex]) < 0:
self.swap(item, self.items[swapIndex])
else:
return
else:
return
def swap(self, itemA, itemB):
self.items[itemA.heapIndex] = itemB
self.items[itemB.heapIndex] = itemA
temp = itemA.heapIndex
itemA.heapIndex = itemB.heapIndex
itemB.heapIndex = temp