Building Max Heap

Heapify Algorithm and Insert Key Operation

#include <bits/stdc++.h>

using namespace std;

//Coverting an array to max heap
void maxHeapify(vector<int> &v, int pos)
{
    int n = v.size();
    int largest = pos;
    int lc = 2 * pos + 1;
    int rc = 2 * pos + 2;

    if (lc < n && v[lc] > v[largest])
    {
        largest = lc;
    }

    if (rc < n && v[rc] > v[largest])
    {
        largest = rc;
    }

    if (largest != pos)
    {
        swap(v[pos], v[largest]);
        maxHeapify(v, largest);
    }

    return;
}

int main()
{
    int k;
    cin >> k;
    vector<int> v;

    for (int i = 0; i < k; i++)
    {
        int num;
        cin >> num;
        v.push_back(num);
    }

    int n = v.size();

    // calling all internal nodes to heapfify
    for (int i = n / 2 - 1; i >= 0; i--)
    {
        maxHeapify(v, i);
    }

    int t;
    cin >> t;

    while (t--)
    {
        int type;
        cin >> type;
        // Insert Key Operation
        if (type == 1)
        {
            int newNum;
            cin >> newNum;
            v.push_back(newNum);

            //Percolate up alogorithm
            int i = v.size() - 1;

            while (i > 0 && v[i] > v[(i - 1) / 2])
            {
                swap(v[i], v[(i - 1) / 2]);
                i = (i - 1) / 2;
            }
        }
        else
        //Get Max Operation
        {
            cout << v[0] << "\n";
        }
    }

    return 0;
}

Last updated