作者:火俊逸香嘉孝 | 来源:互联网 | 2023-08-28 23:23
使用从元素下标HeapSize2-1开始到0,使用MaxHeapify()函数重新建堆。voidmaxHeapify(int[]A,intheapSize,inti){intleft
使用从元素下标HeapSize/2-1开始到0,使用MaxHeapify()函数重新建堆。
void maxHeapify(int []A,int heapSize,int i)
{
int left = 2*i;
int right = 2*i + 1;
int larger = i;
if (left <= heapSize&&A[left] > A[larger])
{
larger = left;
}
if (right <= heapSize&&A[right]>A[larger])
{
larger = right;
}
if (larger != i)
{
int temp = A[i];
A[i] = A[larger];
A[larger] = temp;
maxHeapify(A,heapSize,larger);
}
}
void BuildHeap(int []A,int heapSize)
{
for (int i=heapSize/2-1;i>=0;i++)
{
maxHeapify(A,heapSize,i);
}
}