void AdjustHeap(int *a, int size,int root)//建最大堆
{
if (a == NULL )
{
return;
}
int child = root*2+1;
while (child<size)
{
if ((child + 1) < size && a[child] < a[child + 1])
{
++child;
}
if (a[root]<a[child])
{
swap(a[child], a[root]);
}
root = child;
child = root * 2 + 1;
}
}
void Adjustdown(int *a, int size, int root)//向下调整,将堆顶的数据换到堆底后把长度减一;
{ //再将堆顶数据向下比较,建成最大堆
int child = root * 2 + 1;
while (child < size)
{
if ((child + 1) < size && a[child] < a[child + 1])
{
++child;
}
if (a[child] > a[root])
{
swap(a[child], a[root]);
}
root = child;
child = root * 2 + 1;
}
}
void HeapSort(int *a,int length)
{
if (a == NULL || length <= 0)
{
return;
}
for (int i = (length - 2) / 2; i >= 0; i--)
{
AdjustHeap(a, length, i);
}
for (int i = length - 1; i > 0; i--)
{
int tmp = a[0];
a[0] = a[i];
a[i] = tmp;
Adjustdown(a, i, 0);
}
}