Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int length = 1 ;
- class Heap
- {
- public:
- Build_MinHeap(int arr[])
- {
- int n = length;
- for(int i=n/2;i>=1;i--)
- Min_heapify(arr,i,n);
- }
- Min_heapify(int arr[],int i,int n)
- {
- int leftchild = 2*i;
- int rightchild = 2*i+1;
- int smaller;
- if(leftchild<=n && arr[leftchild]<arr[i])
- smaller = leftchild;
- else
- smaller = i;
- if(rightchild <=n && arr[rightchild]<arr[smaller])
- smaller = rightchild;
- if(smaller != i)
- {
- swap(arr[smaller],arr[i]);
- Min_heapify(arr,smaller,n);
- }
- }
- void min_heap_insert(int arr[],int key,int n)
- {
- length = n+1;
- arr[n+1] = key;
- heap_change_key(arr,11,key);
- }
- void heap_change_key(int arr[],int i,int key)
- {
- while((i > 1) && arr[i/2] > arr[i])
- {
- swap(arr[i],arr[i/2]);
- i = i/2;
- }
- }
- void display( int arr[])
- {
- for(int i = 1;i<= length;i++)
- cout<<arr[i]<<" ";
- cout<<endl<<endl;
- }
- };
- int main()
- {
- Heap obj;
- freopen("input.txt","r",stdin);
- int arr[100];
- int key;
- cin>>key;
- while(cin)
- {
- cin>>arr[length++];
- }
- length -= 2;
- cout<<"Original Min Heap:"<<endl;
- obj.Build_MinHeap(arr);
- obj.display(arr);
- cout<<"After Insert a value: "<<endl;
- obj.min_heap_insert(arr,key,length);
- obj.display(arr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement