class
MinHeap:
harr
=
[]
capacity
=
0
heap_size
=
0
def
__init__(
self
, capacity):
self
.heap_size
=
0
self
.capacity
=
capacity
self
.harr
=
[
0
]
*
capacity
def
MinHeapify(
self
, i):
l
=
self
.left(i)
r
=
self
.right(i)
smallest
=
i
if
l <
self
.heap_size
and
self
.harr[l] <
self
.harr[i]:
smallest
=
l
if
r <
self
.heap_size
and
self
.harr[r] <
self
.harr[smallest]:
smallest
=
r
if
smallest !
=
i:
self
.harr[i],
self
.harr[smallest]
=
self
.harr[smallest],
self
.harr[i]
self
.MinHeapify(smallest)
def
parent(
self
, i):
return
(i
-
1
)
/
/
2
def
left(
self
, i):
return
(
2
*
i
+
1
)
def
right(
self
, i):
return
(
2
*
i
+
2
)
def
insertKey(
self
, k):
if
self
.heap_size
=
=
self
.capacity:
print
(
"\nOverflow: Could not insertKey\n"
)
return
self
.heap_size
+
=
1
i
=
self
.heap_size
-
1
self
.harr[i]
=
k
while
i !
=
0
and
self
.harr[
self
.parent(i)] >
self
.harr[i]:
self
.harr[i],
self
.harr[
self
.parent(i)]
=
self
.harr[
self
.parent(i)],
self
.harr[i]
i
=
self
.parent(i)
def
printSmallerThan(
self
, x, pos
=
0
):
if
pos >
=
self
.heap_size:
return
if
self
.harr[pos] >
=
x:
return
print
(
self
.harr[pos], end
=
" "
)
self
.printSmallerThan(x,
self
.left(pos))
self
.printSmallerThan(x,
self
.right(pos))
def
main():
h
=
MinHeap(
50
)
h.insertKey(
3
)
h.insertKey(
2
)
h.insertKey(
15
)
h.insertKey(
5
)
h.insertKey(
4
)
h.insertKey(
45
)
h.insertKey(
80
)
h.insertKey(
6
)
h.insertKey(
150
)
h.insertKey(
77
)
h.insertKey(
120
)
x
=
100
h.printSmallerThan(x)
if
__name__
=
=
"__main__"
:
main()