Skip to content

Commit 4dd2176

Browse files
committed
Added insertion operations for Min Heap and Max Heap in Python
1 parent 10a0de1 commit 4dd2176

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Insertion in Min Heap and Max Heap
2+
# Author: Suhaani Garg
3+
# Description: Demonstrates how to insert an element in both Min Heap and Max Heap in Python.
4+
5+
import heapq
6+
7+
# ----- MIN HEAP -----
8+
def insert_min_heap(heap, value):
9+
"""Insert an element into a Min Heap."""
10+
heapq.heappush(heap, value)
11+
return heap
12+
13+
# ----- MAX HEAP -----
14+
def insert_max_heap(heap, value):
15+
"""Insert an element into a Max Heap."""
16+
# Python heapq is a Min Heap, so we invert the value for Max Heap
17+
heapq.heappush(heap, -value)
18+
return heap
19+
20+
# ----- DEMO -----
21+
if __name__ == "__main__":
22+
min_heap = []
23+
max_heap = []
24+
25+
# Inserting elements
26+
for num in [10, 4, 15, 20, 0]:
27+
insert_min_heap(min_heap, num)
28+
insert_max_heap(max_heap, num)
29+
30+
print("Min Heap (ascending order):", min_heap)
31+
print("Max Heap (descending order):", [-x for x in max_heap])

0 commit comments

Comments
 (0)