forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.py
More file actions
Latest commit
177 lines (149 loc) · 5 KB
/
Copy pathheap.py
File metadata and controls
177 lines (149 loc) · 5 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
from __future__ importannotations
fromabcimportabstractmethod
fromcollections.abcimportIterable
fromtypingimportGeneric, Protocol, TypeVar
classComparable(Protocol):
@abstractmethod
def__lt__(self: T, other: T) ->bool:
pass
@abstractmethod
def__gt__(self: T, other: T) ->bool:
pass
@abstractmethod
def__eq__(self: T, other: object) ->bool:
pass
T=TypeVar("T", bound=Comparable)
classHeap(Generic[T]):
"""A Max Heap Implementation
>>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]
>>> h = Heap()
>>> h.build_max_heap(unsorted)
>>> h
[209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]
>>>
>>> h.extract_max()
209
>>> h
[201, 107, 25, 103, 11, 15, 1, 9, 7, 5]
>>>
>>> h.insert(100)
>>> h
[201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11]
>>>
>>> h.heap_sort()
>>> h
[1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201]
"""
def__init__(self) ->None:
self.h: list[T] = []
self.heap_size: int=0
def__repr__(self) ->str:
returnstr(self.h)
defparent_index(self, child_idx: int) ->int|None:
"""return the parent index of given child"""
ifchild_idx>0:
return (child_idx-1) //2
returnNone
defleft_child_idx(self, parent_idx: int) ->int|None:
"""
return the left child index if the left child exists.
if not, return None.
"""
left_child_index=2*parent_idx+1
ifleft_child_index<self.heap_size:
returnleft_child_index
returnNone
defright_child_idx(self, parent_idx: int) ->int|None:
"""
return the right child index if the right child exists.
if not, return None.
"""
right_child_index=2*parent_idx+2
ifright_child_index<self.heap_size:
returnright_child_index
returnNone
defmax_heapify(self, index: int) ->None:
"""
correct a single violation of the heap property in a subtree's root.
"""
ifindex<self.heap_size:
violation: int=index
left_child=self.left_child_idx(index)
right_child=self.right_child_idx(index)
# check which child is larger than its parent
ifleft_childisnotNoneandself.h[left_child] >self.h[violation]:
violation=left_child
ifright_childisnotNoneandself.h[right_child] >self.h[violation]:
violation=right_child
# if violation indeed exists
ifviolation!=index:
# swap to fix the violation
self.h[violation], self.h[index] =self.h[index], self.h[violation]
# fix the subsequent violation recursively if any
self.max_heapify(violation)
defbuild_max_heap(self, collection: Iterable[T]) ->None:
"""build max heap from an unsorted array"""
self.h=list(collection)
self.heap_size=len(self.h)
ifself.heap_size>1:
# max_heapify from right to left but exclude leaves (last level)
foriinrange(self.heap_size//2-1, -1, -1):
self.max_heapify(i)
defextract_max(self) ->T:
"""get and remove max from heap"""
ifself.heap_size>=2:
me=self.h[0]
self.h[0] =self.h.pop(-1)
self.heap_size-=1
self.max_heapify(0)
returnme
elifself.heap_size==1:
self.heap_size-=1
returnself.h.pop(-1)
else:
raiseException("Empty heap")
definsert(self, value: T) ->None:
"""insert a new value into the max heap"""
self.h.append(value)
idx= (self.heap_size-1) //2
self.heap_size+=1
whileidx>=0:
self.max_heapify(idx)
idx= (idx-1) //2
defheap_sort(self) ->None:
size=self.heap_size
forjinrange(size-1, 0, -1):
self.h[0], self.h[j] =self.h[j], self.h[0]
self.heap_size-=1
self.max_heapify(0)
self.heap_size=size
if__name__=="__main__":
importdoctest
# run doc test
doctest.testmod()
# demo
forunsortedin [
[0],
[2],
[3, 5],
[5, 3],
[5, 5],
[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 3, 5],
[0, 2, 2, 3, 5],
[2, 5, 3, 0, 2, 3, 0, 3],
[6, 1, 2, 7, 9, 3, 4, 5, 10, 8],
[103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5],
[-45, -2, -5],
]:
print(f"unsorted array: {unsorted}")
heap: Heap[int] =Heap()
heap.build_max_heap(unsorted)
print(f"after build heap: {heap}")
print(f"max value: {heap.extract_max()}")
print(f"after max value removed: {heap}")
heap.insert(100)
print(f"after new value 100 inserted: {heap}")
heap.heap_sort()
print(f"heap-sorted array: {heap}\n")