heap

PHOTO EMBED

Tue Jun 06 2023 08:38:02 GMT+0000 (Coordinated Universal Time)

Saved by @ronin_78 #java

#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;
}
content_copyCOPY