MAX heap - cook the code

Saturday, 11 November 2017

MAX heap

#include<iostream>
using namespace std;
class Heap{
int cmax;
int arr[100];
int Msize;
public:
Heap(){
cmax=0;
Msize=100;
}
int parent(int i){
return (i-1)/2;
}
int lchild(int i){
return 2*i+1;
}
int rchild(int i){
return 2*i+2;
}
void delkey(){

}
void insert(int data){
// check for overflow here
cmax++;
int i=cmax-1;
arr[i]=data;
while(i>0&&arr[(parent(i))]<data){
swap(arr[parent(i)],arr[i]);
i=parent(i);
}
}
int maxextract(){
if(cmax<=0)return -1; //indicate that heap is empty
if(cmax==1){
cmax--;
return arr[0];
}
int data=arr[0];
cmax--;
arr[0]=arr[cmax];
heapfy(0);
return data;
}
void heapfy(int i){
int l=lchild(i);
int r=rchild(i);
int large=i;
if(l<cmax&&arr[l]>arr[large]){
large=l;
}
if(r<cmax&&arr[r]>arr[large]){
large=r;
}
if(large!=i){
swap(arr[i],arr[large]);
heapfy(large);
}
}
int getMAX(){
if(cmax<=0)return -1;// heap is empty
return arr[0];
}
void decreasekey(int i,int newval){
arr[i]=newval;
while(i>0&&arr[parent(i)]<arr[i]){
swap(arr[parent(i)],arr[i]);
i=parent(i);
}
if(i==0)heapfy(0);
}

void deletekey(int i){
decreasekey(i,INT_MAX);
maxextract();
}

};
/*
parent()
leftchild()
rightchild()
getmax()
maxextract()
heapfy()
decreasekey()
deletekey()
insert()
*/
int main(){

Heap x;
x.insert(41);
x.insert(30);
x.insert(60);
x.insert(40);
//x.decreasekey(0,18);
x.deletekey(3);
cout<<x.maxextract()<<endl;
cout<<x.maxextract();

return 0;
}

No comments:

Post a Comment