#include
#include
int left(int i)
{ return (i<<1);
}
int right(int i)
{ return (i<<1+1);
}
void exchange(int A[10],int i,int j)
{ int temp;
temp=A[i-1]; A[i-1]=A[j-1]; A[j-1]=temp;
}
void MAX_HEAPIFY(int A[10],int i,int length,int heapsize)
{ int l,r,largest;
l=left(i); r=right(i);
if(l<=heapsize && A[l-1]>A[i-1])
l=largest;
else
i=largest;
if(r<=heapsize && A[r-1]>A[i-1])
r=largest;
if(i!=largest)
{ exchange(A,i,largest);
MAX_HEAPIFY(A,largest,length,heapsize);
}
}
void BUILD_HEAP(int A[10],int length,int heapsize)
{ for(int i=floor(length/2);i>=1;i--)
MAX_HEAPIFY(A,i,length,heapsize);
}
void HEAPSORT(int A[10],int length,int heapsize)
{ BUILD_HEAP(A,length,heapsize);
for(int i=length;i>1;i--)
{ exchange(A,1,heapsize--);
MAX_HEAPIFY(A,1,length,heapsize);
}
}
int main()
{ int A[10]={12,1,5,2,3,8,6,7,9,15},length=10,heapsize=10;
HEAPSORT(A,length,heapsize);
for(int i=0;i<10;i++)
printf("%d ",A[i]);
}