#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// Creating an array
int arr[] = {4, 10, 3, 5, 1};
// Size of the array
int size = sizeof(arr) / sizeof(arr[0]);
// Building a max heap from the array
make_heap(arr, arr + size);
cout << "Max heap: ";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
// Inserting an element into the heap
int newElement = 7;
arr[size] = newElement;
push_heap(arr, arr + size + 1);
cout << "Max heap after insertion: ";
for (int i = 0; i < size + 1; ++i) {
cout << arr[i] << " ";
}
cout << endl;
// Removing the maximum element from the heap
pop_heap(arr, arr + size + 1);
int maxElement = arr[size];
--size;
cout << "Max element removed: " << maxElement << endl;
cout << "Max heap after removal: ";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter