Advertisement
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 max_heapify(int A[],int i)
- {
- int l,r,largest;
- l=left(i);
- r=right(i);
- if(l<=heap_size && A[l]>A[i])
- largest=l;
- else
- largest=i;
- if(r<=heap_size && A[r]>A[largest])
- largest=r;
- if(largest!=i)
- {
- swap(A[i],A[largest]);
- max_heapify(A,largest);
- }
- }
- void build_max_heap(int A[],int len)
- {
- for(int i=len/2;i>0;i--)
- max_heapify(A,i);
- }
- void heap_sort(int A[],int length)
- {
- int len=length;
- build_max_heap(A,len);
- for(int i=length;i>1;i--)
- {
- swap(A[1],A[i]);
- heap_size--;
- max_heapify(A,1);
- }
- }
- int main()
- {
- cout<<"Heap Size:";
- cin>>heap_size;
- int A[heap_size+1];
- cout<<"UNSORTED INPUT"<<endl;
- for(int i=1;i<heap_size+1;i++)
- {
- cin>>A[i];
- }
- int length=sizeof(A)/sizeof(int)-1;
- cout<<"SORTED: ";
- heap_sort(A,length);
- for(int i=1;i<length+1;i++)
- {
- cout<<A[i]<<" ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement