int[] arr = {3, 9, 2, 1, 4, 5}; BuildMaxHeap(arr); Console.WriteLine(string.Join(", ", arr));
The build max heap process rearranges the array so that each parent node is greater than its children. Starting from the last non-leaf node, heapify is applied upwards. The final array after heapify is [9, 4, 5, 1, 3, 2].
int[] arr = {7, 2, 6, 3, 9, 1}; BuildMinHeap(arr); Console.WriteLine(string.Join(", ", arr));
Applying build min heap rearranges the array so parents are smaller than children. The final array is [1, 2, 3, 7, 9, 6].
void MaxHeapify(int[] arr, int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; MaxHeapify(arr, n, largest); } } void BuildMaxHeap(int[] arr) { int n = arr.Length; for (int i = n / 2 - 1; i >= 0; i--) { MaxHeapify(arr, n, i); } }
The for loop in BuildMaxHeap starts at n/2 and goes down to 0 inclusive. But it should start at n/2 - 1. Because of this, the loop runs one extra time with i = n/2, which is a leaf node index, causing MaxHeapify to recurse infinitely on some inputs, leading to StackOverflowException.
int[] arr = {10, 15, 20, 17, 25}; MaxHeapify(arr, arr.Length, 1); Console.WriteLine(string.Join(", ", arr));
At index 1, the children are at indices 3 and 4 with values 17 and 25. The largest child is 25 at index 4. Swap 15 and 25. Then heapify index 4 which is a leaf, so stop. Result: [10, 25, 20, 17, 15].
Build heap calls heapify starting from the last non-leaf nodes up to the root. Nodes near the bottom have small heights and many nodes, nodes near the top have larger heights but fewer nodes. The total work sums to O(n) because the work per level times number of nodes per level sums linearly.
