class MinHeap:
def __init__(self):
self.heap = []
def insert(self, val):
self.heap.append(val)
self._heapify_up(len(self.heap) - 1)
def remove_min(self):
if not self.heap:
return None
min_val = self.heap[0]
last_val = self.heap.pop()
if self.heap:
self.heap[0] = last_val
self._heapify_down(0)
return min_val
def _heapify_up(self, index):
parent = (index - 1) // 2
while index > 0 and self.heap[index] < self.heap[parent]:
self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index]
index = parent
parent = (index - 1) // 2
def _heapify_down(self, index):
size = len(self.heap)
while True:
left = 2 * index + 1
right = 2 * index + 2
smallest = index
if left < size and self.heap[left] < self.heap[smallest]:
smallest = left
if right < size and self.heap[right] < self.heap[smallest]:
smallest = right
if smallest == index:
break
self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]
index = smallest
# Driver code to compare sorted array and heap operations
# Sorted array operations
sorted_arr = [1, 3, 5, 7, 9]
# Remove min (first element)
removed = sorted_arr.pop(0)
# Insert 2 keeping sorted
insert_pos = 0
while insert_pos < len(sorted_arr) and sorted_arr[insert_pos] < 2:
insert_pos += 1
sorted_arr.insert(insert_pos, 2)
# Heap operations
heap = MinHeap()
for val in [1, 3, 5, 7, 9]:
heap.insert(val)
heap.remove_min()
heap.insert(2)
# Print results
print("Sorted array final:", " -> ".join(map(str, sorted_arr)) + " -> null")
print("Heap final:", " -> ".join(map(str, heap.heap)) + " -> null")removed = sorted_arr.pop(0)
Remove smallest element from front, causes shift of all elements
while insert_pos < len(sorted_arr) and sorted_arr[insert_pos] < 2:
insert_pos += 1
sorted_arr.insert(insert_pos, 2)
Find correct position and insert new element to keep array sorted
Remove smallest element from heap root and reheapify down
Add new element at end and reheapify up to restore heap property
Sorted array final: 2 -> 3 -> 5 -> 7 -> 9 -> null
Heap final: 2 -> 3 -> 5 -> 9 -> 7 -> null