Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

max heap insertion c++

#include<iostream>
using namespace std;
/*Heapify using Bottom up approach*/
void heapify(int a[],int n,int i)
{
	int parent;
	parent = (i-1)/2; //for finding the parent of child
	if(parent>=0)     //Check until index < 0
	{
		if(a[parent]<a[i])
		{
			swap(a[parent],a[i]);
			heapify(a,n,parent); //recursive heapify function
		}
	}
}
/*Inserting the New Element into the Heap*/
void insert(int a[],int &n,int val)
{
	/*Increase the Size of the Array by 1*/
	n=n+1;
	/*Insert the new element at the end of the Array*/
	a[n-1]=val;
	/*Heapify function*/
	heapify(a,n,n-1);
}
/*Printing the Heap*/
void print(int a[],int n)
{
	cout<<"
The Array Representation of Heap is
";
	for(int i=0;i<n;i++)
	{
		cout<<a[i]<<" ";
	}
}
/*Driver Function*/
int main()
{
	/*Initial Max Heap is */
	int a[100]={10,5,3,2,4};
	int n = 5;
	/*The Element to be insert is 15*/
	int val = 15;
	/*Printing the Array*/
	print(a,n);
	/*Insert Function*/
	insert(a,n,val); //here we are passing the 'n' value by reference
	/*Printing the Array*/
	print(a,n);
	return 0;
}
Source by cppsecrets.com #
 
PREVIOUS NEXT
Tagged: #max #heap #insertion
ADD COMMENT
Topic
Name
7+1 =