算法导论 - 3 - Heap sort (数组)

伪代码

1.
max-heapify(A,i)

//assume left and right both are max heap

//pay attention to field 'i' , remember it

l=2*i

r=2*i+1

if l<=A.heap-size and A[i]<A[l]  // l must be within A's scope 
    largest=l

else

    largest=i

if r<=A.heap-size and A[largest]<A[r]  // r must be within A's scope 

    largest=r

if(largest!=i)

    swap(A[largest],A[i])

    max-heapify(A,largest)


2.
build-max-heap(A)

A.heap-size=A.size

mid= |_ A.heap-size/2 _|  // notice that you choose the "|_ _|"

for i=mid downto 1

max-heapify(A,i) 


3.
heap-sort(A)

build-max-heap(A)

for i=A.heap-size downto 2 // downto 2 is enough, '1' don't need to exchange with itself

    swap(A[i],A[1])

    A.heap-size=A.heap-size-1 // this change is importance because it will affect max-heapify !

    max-heapify(A,1)


/**

 *following are the applications of heap in priority queue: INSERT、MAXIMUM、EXTRACT-MAX、INCREASE-KEY 

**/

4.
heap-extract-max(A)

if A.heap-size<1

    error "out of range"

max=A[1]

//similar with heap sort , but A[1] will be abandoned afterward , so don't swap , just '=' and  '-1'

A[1]=A[A.heap-size-1]

A.heap-size=A.heap-size-1

max-heapify(A,1)

return max

5.
heap-increase-key(A,i,x)

if x<A[i]

    error "x is smaller than A[i]"

A[i]=x

while i>1 and A|_i/2_|<A[i]

    swap (A[i],A|_i/2_|)

    i=|_i/2_| // remember to update i


6.
max-heap-insert(A,x)

A.heap-size=A.heap-size+1

A[A.heap-size]=-INF

heap-increase-key(A,A.heap-size,x)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值