1
1
class Heap (object ):
2
-
2
+
3
3
HEAP_SIZE = 10 ;
4
-
4
+
5
5
def __init__ (self ):
6
6
self .heap = [0 ]* Heap .HEAP_SIZE
7
7
self .currentPosition = - 1
8
-
8
+
9
9
def insert (self , item ):
10
-
10
+
11
11
# if heap is full , we print a notification
12
12
if self .isFull ():
13
13
print ("Heap is full" )
@@ -16,7 +16,7 @@ def insert(self, item):
16
16
self .currentPosition += 1
17
17
self .heap [self .currentPosition ] = item
18
18
self .fixUp (self .currentPosition )
19
-
19
+
20
20
def fixUp (self , index ):
21
21
parentIndex = int ((index - 1 )/ 2 )
22
22
while parentIndex >= 0 and self .heap [parentIndex ] < self .heap [index ]:
@@ -27,54 +27,54 @@ def fixUp(self, index):
27
27
# update the index and parentIndex
28
28
index = parentIndex
29
29
parentIndex = int ((index - 1 )/ 2 )
30
-
30
+
31
31
def fixDown (self , index , upto ):
32
32
if upto < 0 :
33
33
upto = self .currentPosition
34
-
34
+
35
35
while index <= upto :
36
36
leftChild = 2 * index + 1
37
37
rightChild = 2 * index + 2
38
-
38
+
39
39
if leftChild <= upto :
40
40
childToSwap = 0
41
41
else :
42
42
if self .heap [leftChild ] < self .heap [rightChild ]:
43
43
childToSwap = leftChild
44
44
else :
45
45
childToSwap = rightChild
46
-
46
+
47
47
if self .heap [index ] < self .heap [childToSwap ]:
48
48
temp = self .heap [index ]
49
49
self .heap [index ] = self .heap [childToSwap ]
50
50
self .heap [childToSwap ] = temp
51
51
else :
52
52
break
53
-
53
+
54
54
index = childToSwap
55
-
55
+
56
56
else :
57
57
return
58
-
58
+
59
59
def heapSort (self ):
60
60
for i in range (0 , self .currentPosition + 1 ):
61
61
temp = self .heap [0 ]
62
62
print ("%d" % temp )
63
63
self .heap [0 ] = self .heap [self .currentPosition - i ]
64
64
self .heap [self .currentPosition - i ] = temp
65
65
self .fixDown (0 , self .currentPosition - i - 1 )
66
-
67
- def getMax ():
66
+
67
+ def getMax (self ):
68
68
result = self .heap [0 ]
69
69
self .currentPosition -= 1
70
70
self .heap [0 ] = self .heap [self .currentPosition ]
71
71
del self .heap [self .currentPosition ]
72
72
self .fixDown (0 , - 1 )
73
73
return result
74
-
74
+
75
75
def isFull (self ):
76
76
return self .currentPosition == Heap .HEAP_SIZE
77
-
77
+
78
78
some_heap = Heap ()
79
79
some_heap .insert (12 )
80
80
some_heap .insert (- 3 )
0 commit comments