Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- class min_heap {
- public:
- int n;
- int a[50];
- void min_input();
- void build_minheap();
- void min_hapify(int i,int n);
- void min_display(int s);
- void min_heapsort();
- void min_heap_insert(int key,int n);
- void heap_chang_key(int i,int key);
- int parent( int i);
- int tree_prestnt(int siz);
- };
- int min_heap::tree_prestnt(int siz){
- int i=1;
- int k=1;
- int j;
- cout<<endl<<endl;
- for(;i<=siz;i*=2){
- for(j=1;j<=i;j++){
- cout<<a[k]<<" ";
- k++;
- if(k>siz)
- return 1;
- }
- cout<<endl;
- }
- }
- int min_heap::parent(int i)
- {
- return (i/2);
- }
- void min_heap::heap_chang_key(int i,int key){
- a[i]=key;
- while((i>1)&&(a[parent(i)]>a[i])){
- swap(a[i],a[parent(i)]);
- i=parent(i);
- }
- }
- void min_heap::min_heap_insert(int key,int n){
- int heap_size=n+1;
- a[n+1]=2147483647;
- heap_chang_key(n+1,key);
- }
- void min_heap::min_heapsort(){
- int i=n;
- for(;i>=2;i--){
- cout<<a[1]<<" ";
- swap(a[1],a[i]);
- n=n-1;
- min_hapify(1,i-1);
- }
- cout<<a[i]<<endl;
- }
- void min_heap::min_display(int s){
- int i;
- cout<<"The heap is "<<endl;
- for(i=1;i<=s;i++)
- cout<<a[i]<<" ";
- cout<<endl;
- }
- void min_heap::min_input(){
- cin>>n;
- for(int i=1;i<=n;i++){
- cin>>a[i];
- }
- }
- void min_heap::build_minheap(){
- int i=n/2;
- for(;i>=1;i--){
- min_hapify(i,n);
- }
- }
- void min_heap::min_hapify(int i,int n){
- int minimul;
- int l=2*i;
- int r=2*i+1;
- if((l<=n)&&(a[l]<a[i])){
- minimul=l;
- }
- else
- minimul=i;
- if((r<=n)&&(a[r]<=a[minimul]))
- minimul=r;
- if(minimul!=i){
- swap(a[i],a[minimul]);
- min_hapify(minimul,n);
- }
- }
- int main(){
- freopen("input.txt","r",stdin);
- min_heap ob;
- ob.min_input();
- ob.build_minheap();
- ob.min_display(ob.n);
- // cout<<"\n THE Sorted heap is "<<endl;
- // ob.min_heapsort();
- int key;
- cin>>key;
- ob.min_heap_insert(key,ob.n);
- ob.min_display(ob.n+1);
- ob.tree_prestnt(ob.n);
- // ob.display();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement