HeapSort-伪码的算法描述整理如下

MAX-HEAPIFY(A, i)

1 l ← LEFT(i)

2 r ← RIGHT(i)

3 if l heap-size[A] and A[l] > A[i]

4     then largest l

5     else largest i

6 if r heap-size[A] and A[r] > A[largest]

7     then largest r

8 if largest i

9     then exchange A[i] A[largest]

10         MAX-HEAPIFY(A, largest)

BUILD-MAX-HEAP(A)

1 heap-size[A] ← length[A]

2 for i length[A]/2 downto 1

3     do MAX-HEAPIFY(A, i)

HEAPSORT(A)

1 BUILD-MAX-HEAP(A)

2 for i length[A] downto 2

3     do exchange A[1] A[i]

4           heap-size[A] ← heap-size[A] - 1

5           MAX-HEAPIFY(A, 1)

   The HEAPSORT procedure takes time O(n lg n), since the call to BUILD-MAX-HEAP takes time O(n) and each of the n - 1 calls to MAX-HEAPIFY takes time O(lg n).

   Heapsort is an excellent algorithm, but a good implementation of quicksort, usually beats it in practice.

   Heapsort is an excellent algorithm, but a good implementation of quicksort, usually beats it in practice.

   Heapsort is an excellent algorithm, but a good implementation of quicksort, usually beats it in practice.

priority-queue operation :

HEAP-MAXIMUM(A)

1 return A[1]

The procedure HEAP-MAXIMUM implements the MAXIMUM operation in Θ(1) time.

 

HEAP-EXTRACT-MAX(A)

1 if heap-size[A] < 1

2     then error "heap underflow"

3 max A[1]

4 A [1] ← A[heap-size[A]]

5 heap-size[A] ← heap-size[A] - 1

6 MAX-HEAPIFY(A, 1)

7 return max

 

The running time of HEAP-EXTRACT-MAX is O(lg n), since it performs only a constant amount of work on top of the O(lg n) time for MAX-HEAPIFY.

 

 

HEAP-INCREASE-KEY(A, i, key)

1 if key < A[i]

2     then error "new key is smaller than current key"

3 A [i] ← key

4 while i > 1 and A[PARENT(i)] < A[i]

5     do exchange A[i] A[PARENT(i)]

6         i ← PARENT(i)

 

The running time of  HEAP-INCREASE-KEY on an n-element heap is O(lg n), since the path traced from the node updated in line 3 to the root has length O(lg n).

 

MAX-HEAP-INSERT(A, key)

1 heap-size[A] ← heap-size[A] + 1

2 A [heap-size[A]] ← -∞

3 HEAP-INCREASE-KEY(A, heap-size[A], key)

 

The running time of MAX-HEAP-INSERT on an n-element heap is O(lg n).

In summary, a heap can support any priority-queue operation on a set of size n in O(lg n)

time.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值