0% found this document useful (0 votes)
2 views1 page

C++ Max Heap Construction Algorithm

The document presents a C++ implementation of a max heap algorithm. It includes a 'maxHeapify' function to maintain the max heap property and a 'buildMaxHeap' function to construct a max heap from an array. The functions utilize recursion and swapping to ensure the largest element is at the root of the heap.

Uploaded by

1324511528zxm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

C++ Max Heap Construction Algorithm

The document presents a C++ implementation of a max heap algorithm. It includes a 'maxHeapify' function to maintain the max heap property and a 'buildMaxHeap' function to construct a max heap from an array. The functions utilize recursion and swapping to ensure the largest element is at the root of the heap.

Uploaded by

1324511528zxm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Algorithm

## Buildheap
```cpp
class Solution {
public:
void maxHeapify(vector<int>& arr, int i, int heapSize) {
int left = i * 2 + 1, right = i * 2 + 2, largest = i;
if (left < heapSize && arr[left] > arr[largest]) {
largest = left;
}
if (right < heapSize && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
swap(arr[i], arr[largest]);
maxHeapify(arr, largest, heapSize);
}
}

void buildMaxHeap(vector<int>& arr, int heapSize) {


for (int i = heapSize / 2; i >= 0; --i) {
maxHeapify(arr, i, heapSize);
}
}
}
```

You might also like