将小顶堆转换为大顶堆

使用从元素下标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);
	}
}









你可能感兴趣的:(将小顶堆转换为大顶堆)