Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * This is a simple max_heap
- * function names are those used in CLRS
- */
- #include <cstdio>
- #include <algorithm>
- #include <vector>
- using namespace std;
- //these functions are inline to avoid function-call overload, could have used macros as well
- inline int left(int x)
- {
- return x*2;
- }
- inline int right(int x)
- {
- return x*2+1;
- }
- inline int parent(int x)
- {
- return x/2;
- }
- void max_heapify(vector<int> &array,int root,int heap_size)
- {
- int maxi=root;
- if(left(root)<=heap_size and array[left(root)]>array[maxi])
- maxi=left(root);
- if(right(root)<=heap_size and array[right(root)]>array[maxi])
- maxi=right(root);
- if(maxi==root)
- return;
- swap(array[maxi],array[root]);
- max_heapify(array,maxi,heap_size);
- }
- void make_max_heap(vector<int> &array)
- {
- int heap_size=array.size()-1;
- for(int i=heap_size/2+1;i>=1;--i)
- max_heapify(array,i,heap_size);
- }
- void heap_sort(vector<int> &array)
- {
- make_max_heap(array);
- int heap_size=array.size()-1;
- while(heap_size)
- {
- swap(array[1],array[heap_size]);
- heap_size--;
- max_heapify(array,1,heap_size);
- }
- }
- int main()
- {
- int n;
- scanf("%d",&n);
- vector<int> x;
- x.push_back(-1);
- x.resize(n+1,0);
- for(int i=0;i<n;++i)
- scanf("%d",&x[i+1]);
- heap_sort(x);
- for(int i=1;i<x.size();++i)
- printf("%d ",x[i]);
- printf("\n");
- return -0;
- }
Advertisement
Add Comment
Please, Sign In to add comment