0% found this document useful (0 votes)
5 views1 page

Array Based Min Heap

The document describes a MinHeap class implemented in Python, which allows for the insertion of values while maintaining the heap property. It includes methods for inserting values and restoring the heap structure through a heapify-up process. A test case demonstrates the functionality by inserting a set of values and printing the resulting min heap as an array.

Uploaded by

Kalyan Mutta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Array Based Min Heap

The document describes a MinHeap class implemented in Python, which allows for the insertion of values while maintaining the heap property. It includes methods for inserting values and restoring the heap structure through a heapify-up process. A test case demonstrates the functionality by inserting a set of values and printing the resulting min heap as an array.

Uploaded by

Kalyan Mutta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

MIN HEAP ARRAY BASED

class MinHeap:
def __init__(self):
self.heap = []

def insert(self, value):


self.heap.append(value) # Add at the end
self._heapify_up(len(self.heap) - 1) # Restore heap property

def _heapify_up(self, index):


parent_index = (index - 1) // 2
while index > 0 and self.heap[index] < self.heap[parent_index]:
self.heap[index], self.heap[parent_index] = self.heap[parent_index],
self.heap[index] # Swap
index = parent_index
parent_index = (index - 1) // 2

def get_heap(self):
return self.heap

# Test the Min Heap


values = [10, 7, 11, 5, 4, 13]
min_heap = MinHeap()
for v in values:
min_heap.insert(v)

# Print the heap as an array


print("Min Heap as array:", min_heap.get_heap())

You might also like