您好,登錄后才能下訂單哦!
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)//向下調(diào)整,將堆頂?shù)臄?shù)據(jù)換到堆底后把長度減一;
{ //再將堆頂數(shù)據(jù)向下比較,建成最大堆
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);
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。