Skip to content

Commit 2c4404f

Browse files
committed
Heaps
1 parent 12ec380 commit 2c4404f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

PQ & Heap/Heaps.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Heap:
2+
def __init__(self):
3+
self._maxsize = 10
4+
self._data = [-1] * self._maxsize
5+
self._csize = 0
6+
7+
def __len__(self):
8+
return len(self._data)
9+
10+
def isempty(self):
11+
return len(self._data) == 0
12+
13+
def insert(self, e):
14+
if self._csize == self._maxsize:
15+
print('No Space in Heap')
16+
return
17+
self._csize = self._csize + 1
18+
hi = self._csize
19+
while hi > 1 and e > self._data[hi // 2]:
20+
self._data[hi] = self._data[hi // 2]
21+
hi = hi // 2
22+
self._data[hi] = e
23+
24+
def max(self):
25+
if self._csize == 0:
26+
print('Heap is Empty')
27+
return
28+
return self._data[1]
29+
30+
def deletemax(self):
31+
if self._csize == 0:
32+
print('Heap is Empty')
33+
return
34+
e = self._data[1]
35+
self._data[1] = self._data[self._csize]
36+
self._data[self._csize] = -1
37+
self._csize = self._csize - 1
38+
i = 1
39+
j = i * 2
40+
while j <= self._csize:
41+
if self._data[j] < self._data[j+1]:
42+
j = j + 1
43+
if self._data[i] < self._data[j]:
44+
temp = self._data[i]
45+
self._data[i] = self._data[j]
46+
self._data[j] = temp
47+
i = j
48+
j = i * 2
49+
else:
50+
break
51+
return e
52+

0 commit comments

Comments
 (0)