This repository has been archived by the owner on Nov 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
heap.py
69 lines (43 loc) · 1.44 KB
/
heap.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
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: bt3gl
class Heap:
def __init__(self):
self.heap = []
def heapify(self, n, i):
largest = i
left_children = 2 * i + 1
right_children = 2 * i + 2
if left_children < n and self.heap[i] < self.heap[left_children]:
largest = left_children
if right_children < n and self.heap[largest] < self.heap[right_children]:
largest = right_children
if largest != i:
self.heap[i], self.heap[largest] = self.heap[largest], self.heap[i]
self.heapify(n, largest)
def insert(self, num):
size = len(self.heap)
if size == 0:
self.heap.append(num)
else:
self.heap.append(num)
for i in range((size // 2) - 1, -1, -1):
self.heapify(size, i)
def delete_node(self, num):
size = len(self.heap)
i = 0
for i in range(size):
if num == self.heap[i]:
break
self.heap[i], self.heap[size - 1] = self.heap[size - 1], self.heap[i]
self.heap.remove(size - 1)
for i in range((len(self.heap) // 2) - 1, -1, -1):
self.heapify(len(self.heap), i)
if __name__ == '__main__':
h = Heap()
for n in [10, 4, 9, 8, 1, 2]:
h.insert(n)
print (f'Max-heap array: {h.heap}')
n = 2
h.delete_node(n)
print(f'After deleting {n}: {h.heap}')