Heap Logic (C++)

← Back to Visualizer
// Standard Max-Heapify Algorithm
void heapify(int arr[], int n, int i) {
    int largest = i; 
    int l = 2 * i + 1; // Left child index
    int r = 2 * i + 2; // Right child index

    // If left child is larger than root
    if (l < n && arr[l] > arr[largest])
        largest = l;

    // If right child is larger than largest so far
    if (r < n && arr[r] > arr[largest])
        largest = r;

    // If largest is not root, swap and continue
    if (largest != i) {
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);
    }
}

Parent Index

To find the parent of a node at index i:

Parent = (i - 1) / 2

Left Child

To find the left child of a node at index i:

Left = 2 * i + 1

Right Child

To find the right child of a node at index i:

Right = 2 * i + 2