Insert function code in heap c++ | heap implementation

This is the code for inserting a new element in a heap. since the property of the heap violates after inserting the element. we will convert it into a heap again.

considering 1 -index array : 

Since we are considering 1 index array here, we take 0 at index 0 . and work on the array from index 1.

Below is the code implemented : 

// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;
void insert(int y, vector<int>& nums)
{
    nums.push_back(y);
    int index = nums.size()-1;
    while(y > nums[index/2] && index/2 >=1)
    {  
        nums[index] = nums[index/2];
        index = index /2;
    }
    nums[index] = y;
}
void printarr(vector<int>&x)
{
    for(int i =1 ;  i < x.size() ; i++)
    {
        cout << x[i] << " ";
    }
}
int main() {
   
    vector<int>x = {0, 30 , 20 , 15 , 5 ,10, 12, 6};
    insert(40 , x);
    printarr(x);
    return 0;
}



For 0 - indexed array : 

// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;
void insert(int y, vector<int>& nums)
{
    nums.push_back(y);
    int index = nums.size()-1;
    while(y > nums[index/2])
    {  
        nums[index] = nums[index/2];
        if(index == 0)
        {
            break ;
        }
        index = index /2;
    }
    nums[index] = y;
}
void printarr(vector<int>&x)
{
    for(int i =0 ;  i < x.size() ; i++)
    {
        cout << x[i] << " ";
    }
}
int main() {
   
    vector<int>x = {30 , 20 , 15 , 5 ,10, 12, 6};
    insert(40 , x);
    printarr(x);
    return 0;
}



Comments