Heapify is the process of converting an unsorted array into a valid min-heap or max-heap in O(n) time. It ensures the structure and order properties of a heap are satisfied.
[50, 80, 40, 20, 30, 90, 60, 10, 70]).[ -, 10, 20, 40, 30, 80, 90, 60, 70, 50 ]).n // 2 (where n is the number of elements).n//2 + 1 to n) already satisfy the heap property.def heapify(arr):
n = len(arr)
# Start from the last non-leaf node and move upwards
for i in range(n // 2, 0, -1):
percolate_down(arr, i, n)
def percolate_down(arr, i, n):
smallest = i # Assume current node is the smallest
left = 2 * i # Left child index
right = 2 * i + 1 # Right child index
# Check if left child exists and is smaller than current node
if left < n and arr[left] < arr[smallest]:
smallest = left
# Check if right child exists and is smaller than current node
if right < n and arr[right] < arr[smallest]:
smallest = right
# If the smallest is not the current node, swap and continue percolating down
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i]
percolate_down(arr, smallest, n) # Recur for the affected subtree
[50, 80, 40, 20, 30, 90, 60, 10, 70][ -, 50, 80, 40, 20, 30, 90, 60, 10, 70 ]n//2 = 4):
20 (index 4): Compare with children 10 and 70. Swap with 10.40 (index 3): Compare with children 90 and 60. No swap needed.80 (index 2): Compare with children 30 and 10. Swap with 10.50 (index 1): Compare with children 10 and 40. Swap with 10.