#include <stdio.h>
#define BOOL int
#define FALSE 0
#define TRUE 1
#define MAXSIZE 8
typedef int Type;
void swap(Type *a,Type *b)
{
Type t;
t=*a;
*a=*b;
*b=t;
}
void print(Type H[],int n)
{
int i;
for(i=0;i<=MAXSIZE;i++)
printf("%3d",H[i]);
}
void sift_down(Type H[],int n,int i)
{
BOOL done=FALSE;
if((2*i)<=n)
{
while(!done&&(i=2*i)<=n)
{
if(i+1<=n&&H[i+1]>H[i])
i=i+1;
if(H[i/2]<H[i])
swap(&H[i/2],&H[i]);
else done=TRUE;
}
}
}
void make_heap(Type H[],int n)
{
int i;
H[n]=H[0];
for(i=n/2;i>=1;i--)
sift_down(H,n,i);
}
void heap_sort(Type H[],int n)
{
int i;
make_heap(H,n);
printf("/n中间过程为:/n");
for(i=n;i>1;i--)
{
print(H,n);
printf("/n");
swap(&H[1],&H[i]);
sift_down(H,i-1,1);
}
}
void main()
{
int i;
Type H[MAXSIZE+1];
printf("请输入一个长度为%d的数组:/n",MAXSIZE);
for(i=0;i<MAXSIZE;i++)
scanf("%d",&H[i]);
heap_sort(H,MAXSIZE);
printf("/n经过堆排序后的数组为:/n");
print(H,MAXSIZE);
printf("/n/n");
}