#include<iostream> using namespace std; int parent(int i) { return i/2; } int left(int i) { return 2*i; } int right(int i) { return 2*i + 1; } void swap(int &a, int &b) { int t = a; a = b; b = t; } void max_heapify(int arr[],int size, int i) { int l = left(i); int r = right(i); int largest = i; if(l<size && arr[l]>arr[largest]) largest = l; if(r<size && arr[r] > arr[largest]) largest = r; if(largest != i) { swap(arr[i], arr[largest]); max_heapify(arr,size,largest); } } void build_max_heap(int arr[],int size) { int i = 0; for(i=size/2; i>=0; i--) max_heapify(arr,size,i); } void print_arr(int arr[], int size) { for(int i=0; i<size; i++) cout<<arr[i]<<" "; cout<<endl; } void heapsort(int arr[], int size) { cout<<"before heap sorting..."<<endl; print_arr(arr,size); int heap_size = size; build_max_heap(arr,size); for(int i=size-1; i>0; i--) { swap(arr[0],arr[i]); heap_size--; max_heapify(arr,heap_size,0); } cout<<"After heap sorting..."<<endl; print_arr(arr,size); } int main() { int i = 0; int n; int arr[1000]; cout<<"please input the size of array!"<<endl; cin>>n; cout<<"plead input the "<<n<<" numbers!"<<endl; for(i = 0; i<n; i++) cin>>arr[i]; heapsort(arr,n); return 0; }