Heapify Algorithm

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.


1. Heapify Overview


2. Steps to Heapify

  1. Identify Last Non-Leaf Node:
  2. Percolate Down:

3. Heapify Algorithm (Min-Heap)

Python Implementation

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

4. Example Walkthrough

Input Array: [50, 80, 40, 20, 30, 90, 60, 10, 70]

  1. Add Dummy Element: Insert at index 0 for 1-based indexing.
  2. Heapify Process: