/* * This is a simple max_heap * function names are those used in CLRS */ #include #include #include 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 &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 &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 &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 x; x.push_back(-1); x.resize(n+1,0); for(int i=0;i