def heapify(arr, n, i): smallest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] < arr[smallest]: smallest = left if right < n and arr[right] < arr[smallest]: smallest = right if smallest != i: arr[i], arr[smallest] = arr[smallest], arr[i] heapify(arr, n, smallest) def build_min_heap(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) arr = [4, 10, 3, 5, 1] build_min_heap(arr) print(' -> '.join(map(str, arr)) + ' -> null')
The build_min_heap function heapifies the array from the last non-leaf node upwards. After heapify, the smallest element is at the root, and the array represents a min-heap.
The final heap array is [1, 4, 3, 5, 10], printed as '1 -> 4 -> 3 -> 5 -> 10 -> null'.
def heapify(arr, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) def build_max_heap(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) arr = [2, 7, 6, 3, 9] build_max_heap(arr) print(' -> '.join(map(str, arr)) + ' -> null')
After building the max-heap, the largest element is at the root. The array becomes [9, 7, 6, 3, 2].
def heapify(arr, n, i): smallest = i left = 2 * i + 1 right = 2 * i + 2 if left <= n and arr[left] < arr[smallest]: smallest = left if right <= n and arr[right] < arr[smallest]: smallest = right if smallest != i: arr[i], arr[smallest] = arr[smallest], arr[i] heapify(arr, n, smallest) arr = [3, 1, 0, 5, 2, 4] heapify(arr, len(arr), 0) print(arr)
The condition uses 'left <= n' and 'right <= n', but valid indices are less than n. This causes an IndexError when accessing arr[n].
def heapify(arr, n, i): smallest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] < arr[smallest]: smallest = left if right < n and arr[right] < arr[smallest]: smallest = right if smallest != i: arr[i], arr[smallest] = arr[smallest], arr[i] heapify(arr, n, smallest) arr = [9, 4, 7, 1, 3, 6] heapify(arr, 6, 1) print(' -> '.join(map(str, arr)) + ' -> null')
Starting at index 1 (value 4), left child is 3 (index 3), right child is 4 (index 4). The smallest is 1 at index 3, so swap 4 and 1.
Then heapify at index 3 (value 4) has no children smaller, so stop.
Final array: [9, 1, 7, 4, 3, 6]
Although heapify can take O(log n) time, it is called on fewer nodes at higher depths. The total time sums to O(n).
