//建堆,运行时间的界T(n) =O(N)
BuildHeap(A)
n = length(A)
for i = n/2 downto 1 do //从非叶子节点开始,自底往上,使A变成最大堆
Max_Heapify(A, i, n)
end
//调整为最大堆 ,T(n) = O(lgn)
Max_Heapify(A,idx,max) //idx:数组开始的下标,max:最大的数组下标
left = 2*idx
right = 2*idx
if(left<max and A[left]>A[idx]) then
largest = left
else
largest = idx
if(right < max and A[right]>A[largest]) then
largest = ritht
if(largest != idx) then
exchange A[largest] with A[idx]
Max_Heapify(A,largest,max) //交换位置后,还需要调整它的子树
end
HeapSort(A)
BuildHeap(A)
for i = length(A) downto 2 do
exchange A[1] with A[i] //把最大堆根节点与最后一个互换
Max_Heapify(A,1, i-1) //把交互后的排除在堆之外,重新从1到i-1,调整堆
end
网友评论