#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<xfunctional>
using namespace std;
typedef struct heap{
int arr_size;
int heap_size;
int *arr;
}heap;
void Tune(heap& h,int start){
int i = start;
if (2 * i > h.heap_size) return;
int index=-1;
int max_temp = h.arr[i];
if (h.arr[2 * i] > h.arr[i]){
index = 2 * i;
max_temp=h.arr[index];
}
if (2 * i + 1 <= h.heap_size){
if (h.arr[2 * i + 1] > max_temp){
max_temp = h.arr[2*i+1];
index = 2 * i + 1;
}
}
if (index == -1) return;
else{
swap(h.arr[index],h.arr[i]);
Tune(h,index);
}
}
void BuildHeap(heap &h){
for (int i = h.heap_size / 2; i >0; i--){
Tune(h,i);
}
}
void heap_sort(heap &h){
for (int i = h.heap_size; i > 1; i--){
swap(h.arr[1], h.arr[h.heap_size]);
h.heap_size--;
Tune(h,1);
}
}
int main(){
heap h;
cout << "Input the size of the array:";
cin >> h.arr_size;
h.arr = new int[h.arr_size+1];
h.heap_size = h.arr_size;
cout << "Input the element:";
for (int i = 1; i <= h.arr_size; i++) cin >> h.arr[i];
BuildHeap(h);
cout << "After build:";
for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i] << " ";
cout << endl;
heap_sort(h);
cout << "After sort:";
for (int i = 1; i <= h.arr_size; i++) cout << h.arr[i]<<" ";
cout << endl;
system("pause");
return 0;
}