/*-------------HeapSort------------------------
Edit by hackicer
QQ;361935233
a[0]:是要排序的数组的大小,a[1] 到 a[a[0]]是要排序的数组
----------------------------------------*/
#include<iostream>
using namespace std;
#define PARENT(i) (i/2)
#define LEFT(i) (2*i)
#define RIGHT(i) (2*i+1)
void exchange( int &x,int &y )
{
int temp = 0;
if( x > y )
{
temp = x;
x = y;
y = temp;
}
}
void HeadIfy(int a[],int i,int n)
{
int left = LEFT(i);
int right = RIGHT(i);
int largest = i;
bool flag = false;
if( right > n )
{
flag = true;
}
else
{
if( a[left] >= a[right] )
{
flag = true;
}
}
if(flag)
{
if( left <= n )
{
if( a[left] > a[i] )
{
largest = left;
}
}
}
else
{
if( right <= n )
{
if( a[right] > a[i] )
{
largest = right;
}
}
}
if( largest != i )
{
exchange(a[largest],a[i]);
HeadIfy(a,largest,n);
}
}
void BuildHeap( int a[],int n )
{
for(int i = n/2 ; i >= 1 ; i-- )
{
HeadIfy(a,i,n);
}
}
void HeapSort(int a[],int heap_size)
{
int i;
BuildHeap(a,heap_size);
for (i = heap_size;i >= 2; i--)
{
int temp;
temp = a[1];
a[1] = a[i];
a[i] = temp;
HeadIfy(a,1,i-1);
}
}
int main()
{
int a[] = { 11,4,1,3,2,16,9,10,14,8,7,23};
HeapSort(a,a[0]);
for( int i = 1 ; i <= a[0] ; i++ )
{
cout<<a[i]<<endl;
}
return 0;
}