#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;
}
Williams Algorithm: top downwhile not end of array, if heap is empty, place item at root; else, place item at bottom of heap; while (child > parent) swap(parent, child); go to next array element; end
Williams Algorithm: top downwhile not end of array, if heap is empty, place item at root; else, place item at bottom of heap; while (child < parent) swap(parent, child); go to next array element; end