Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int heap_size;
- int left(int i)
- {
- return 2*i;
- }
- int right(int i)
- {
- return 2*i+1;
- }
- int parent(int i)
- {
- return i/2;
- }
- void min_heapify(int A[],int i)
- {
- int l,r,smallest;
- l=left(i);
- r=right(i);
- if(l<=heap_size && A[l]<A[i])
- smallest=l;
- else
- smallest=i;
- if(r<=heap_size && A[r]<A[smallest])
- smallest=r;
- if(smallest!=i)
- {
- swap(A[i],A[smallest]);
- min_heapify(A,smallest);
- }
- }
- void build_min_heap(int h[])
- {
- for(int i=heap_size/2; i>0; i--)
- min_heapify(h,i);
- }
- int heap_min(int h[])
- {
- return h[1];
- }
- int heap_extract_min(int h[])
- {
- int mn;
- if(heap_size<=0)
- cout<<"Underflow"<<endl;
- else
- {
- mn=h[1];
- h[1]=h[heap_size];
- heap_size--;
- min_heapify(h,1);
- return mn;
- }
- build_min_heap(h);
- }
- void heap_decrease_key(int h[],int i, int key)
- {
- if(h[i]<key)
- {
- cout<<"ERROR";
- return;
- }
- else
- {
- h[i]=key;
- while(i>1&&h[parent(i)]>h[i])
- {
- swap(h[i],h[parent(i)]);
- i=parent(i);
- }
- }
- build_min_heap(h);
- }
- void display(int h[])
- {
- for(int i=1; i<=heap_size; i++)
- cout<<h[i]<<" ";
- }
- int main()
- {
- int h[100];
- cin>>heap_size;
- for(int i=1; i<=heap_size; i++)
- {
- cin>>h[i];
- }
- build_min_heap(h);
- cout<<"MIN HEAP is"<<endl;
- display(h);
- heap_decrease_key(h,2,1);
- cout<<"\nHeap decreased key"<<endl;
- display(h);
- heap_extract_min(h);
- cout<<"\nMin extracted"<<endl;
- display(h);
- }
Advertisement
Add Comment
Please, Sign In to add comment