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);
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。