//from 算法导论
#include <iostream>
using namespace std;
int left_place(int );
int right_place(int);
void swap_two(int &,int &);
void Max_HEAP(int* ,int ,int);
void build_HEAP(int *,int );
void Heap_sort(int *,int);
int left_place(int i)
{
return 2*i;
}
int right_place(int i)
{
return 2*i+1;
}
void swap_two (int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void Max_HEAP(int *A,int i,int heap_size)
{
int l,r,largest=0;
l=left_place(i);
r=right_place(i);
if (l>heap_size)
{
return;
}
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_two(A[i],A[largest]);
Max_HEAP(A,largest,heap_size);
}
else
{
i++;
Max_HEAP(A,i,heap_size);
}
}
void build_HEAP(int *A,int len)
{
for (int i=len/2;i>=1;i--)
{
Max_HEAP(A,i,len);
}
}
void Heap_sort(int *A,int len)
{
build_HEAP(A,len);
for (int i=len;i>=2;i--)
{
swap_two(A[1],A[i]);
len--;
Max_HEAP(A,1,len);
}
}
int main()
{
int n;
cout<<"input sort numbers\n";
cin>>n;
int *A=new int[n+1];
for (int i=1;i<=n;i++)
{
cin>>A[i];
}
build_HEAP(A,n);
cout<<"print HEAPED data \n";
for (int i=1;i<=n;i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
cout<<"Heap_sort data \n";
Heap_sort(A,n);
for (int i=1;i<=n;i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
return 0;
}