1- # In this approach Bubble down (sink) approach is used to create min heap
2- def build_min_heap (arr ):
3- n = len (arr )
4- def minHeapify (arr ,n ,i ):
5- smallest = i
6- left = 2 * i + 1
7- right = 2 * i + 2
8- if left < n and arr [left ]< arr [smallest ]:
9- smallest = left
10-
11- if right < n and arr [right ]< arr [smallest ]:
12- smallest = right
13- if smallest != i :
14- arr [i ] , arr [smallest ] = arr [smallest ], arr [i ]
15- minHeapify (arr ,n ,smallest )
16-
17- # Start from the last non-leaf node and move upwards
18- for i in range (n // 2 - 1 ,- 1 ,- 1 ):
19- minHeapify (arr ,n ,i )
20- return arr
1+ def min_heapify (arr , n , i ):
2+ """
3+ Ensures the subtree rooted at index `i` satisfies the min-heap property.
214
22- arr = [4 , 10 , 3 , 5 , 1 ]
5+ Parameters:
6+ arr (list): The array representing the heap.
7+ n (int): The size of the heap.
8+ i (int): The index of the root of the subtree to heapify.
9+ """
10+ smallest = i # Assume the current root is the smallest
11+ left = 2 * i + 1 # Index of left child
12+ right = 2 * i + 2 # Index of right child
13+
14+ # Check if the left child exists and is smaller than the root
15+ if left < n and arr [left ] < arr [smallest ]:
16+ smallest = left
17+
18+ # Check if the right child exists and is smaller than the smallest so far
19+ if right < n and arr [right ] < arr [smallest ]:
20+ smallest = right
21+
22+ # If the smallest is not the root, swap and heapify the affected subtree
23+ if smallest != i :
24+ arr [i ], arr [smallest ] = arr [smallest ], arr [i ] # Swap
25+ min_heapify (arr , n , smallest ) # Recursively heapify the affected subtree
26+
27+
28+ def build_min_heap (arr ):
29+ """
30+ Converts an array into a min-heap using the `MIN-HEAPIFY` function.
31+
32+ Parameters:
33+ arr (list): The array to be converted into a min-heap.
34+ """
35+ n = len (arr ) # Size of the heap
36+
37+ # Start from the last non-leaf node and move upwards
38+ for i in range (n // 2 - 1 , - 1 , - 1 ):
39+ min_heapify (arr , n , i )
40+
41+ def insertInHeap (heap ,value ):
42+ if heap is None :
43+ heap = []
44+ heap .append (value )
45+ i = len (heap )- 1
46+ while i > 0 :
47+ parentIndex = (i - 1 )// 2
48+ if heap [parentIndex ]> heap [i ]:
49+ heap [parentIndex ],heap [i ] = heap [i ],heap [parentIndex ]
50+ i = parentIndex
51+ else :
52+ break
53+
54+ arr = [14 , 10 , 13 , 5 , 1 ,7 ,9 ]
55+
2356build_min_heap (arr )
24- print (arr )
57+ insertInHeap (arr ,6 )
58+ print (arr )
0 commit comments