void AdjustHeap(int a[],int rootIndex,int maxIndex)
{
if (rootIndex > maxIndex)
{
return;
}
int lChild = 2 * rootIndex + 1;
int rChild = 2 * rootIndex + 2;
int index = rootIndex;
if (lChild <= maxIndex && a[index] < a[lChild]) index = lChild;
if (rChild <= maxIndex && a[index] < a[rChild]) index = rChild;
if ( index != rootIndex)
{
int temp = a[index];
a[index] = a[rootIndex];
a[rootIndex] = temp;
AdjustHeap(a,index,maxIndex);
}
}
void HeapSort(int a[],int n)
{
int i = ( n - 2 )/2;
for (;i>= 0;--i)
{
AdjustHeap(a,i,n-1);
}
for (i = 0; i < n;++i)
{
int temp = a[0];
a[0] = a[n-1-i];
a[n-1-i] = temp;
AdjustHeap(a,0,n-2-i);
}
}堆排序
最新推荐文章于 2024-06-09 16:03:45 发布
31万+

被折叠的 条评论
为什么被折叠?



