#include<iostream>
using namespace std;
class heap
{
int *arr;
int capacity;
public:
int heap_size;
heap(int cap)
{
capacity=cap;
heap_size=0;
arr=new int[cap];
}
int parent(int i)
{
return ((i-1)/2);
}
int left(int i)
{
return(2*i+1);
}
int right(int i)
{
return (2*i+2);
}
void insert(int k)
{
if(heap_size==capacity)
{
cout<<"nheap is fulln";
return;
}
heap_size++;
int i=heap_size-1;
arr[i]=k;
while(i!=0 && arr[parent(i)]>arr[i])
{
swap(&arr[parent(i)],&arr[i]);
i=parent(i);
}
}
int deletee()
{
if(heap_size<=0)
{
return INT_MAX;
}
if(heap_size==1)
{
heap_size--;
return arr[0];
}
int root=arr[0];
arr[0]=arr[heap_size-1];
heap_size--;
heapify(0);
return root;
}
void heapify(int i)
{
int l=left(i);
int r=right(i);
int smallest=i;
if(l<heap_size && arr[l]<arr[smallest])
{
smallest=l;
}
if(r<heap_size && arr[r]<arr[smallest])
{
smallest=r;
}
if(smallest!=i)
{
swap(&arr[i],&arr[smallest]);
heapify(smallest);
}
}
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
};
int main()
{ heap h(11);
h.insert(3);
h.insert(2);
h.insert(15);
h.insert(5);
h.insert(4);
h.insert(45);
h.insert(25);
h.insert(35);
while(h.heap_size>0)
{
cout<<h.deletee()<<"t";
}
}
0 Comments