HeapSort堆排序的理解和实现

Heapsort堆排序的实现可以分解为两个函数的实现,下面分别对这两个函数进行说明。
1. BUILD-MAX-HEAP(A)
即创建一个最大堆,最大堆的性质是A[Parent(i)]>=A[i]。创建最大堆的过程即给定一个未经排序过的序列,通过函数1实现最大堆的性质,生成一个类似于完全二叉树的结构。
Function Build-Max-Heap(A) is to build a heap that for each nodes and leaves i except root A[Parent(i)]>=A[i], creating a complete binary tree.

算法说明:

A.heap-size = A.length
for i = ⌊A.length/2⌋ downto 1
    MAX-HEAPIFY(A,i)

正确性求证:
设置一个循环不变量:每次第2-3行的循环开始时,设循环不变量是:每个结点i+1,i + 2,…., n 是最大堆的根。
To show why BUILD-MAX-HEAP works correctly we use following loop invariant:
At the start of each iteration for loop of line 2-3, each node i + 1, i + 2, ….., n is the root of max-heap.

(1)初态 :在循环开始之前,i = ⌊n/2⌋。节点⌊n/2⌋+1, ⌊n/2⌋+2,…,n是叶子结点。每个叶子节点组成一个没有孩子的最大堆。
Initialization: Prior to the first iteration of the loop, i = ⌊n/2⌋, each node ⌊n/2⌋+1, ⌊n/2⌋+2,…,n is a leaf thus the root of a trivial max-heap.
(2) 保持: 从i = ⌊n/2⌋开始循环,随着i的递减,除了根结点,其余结点都满足A[Parent(i)]>=A[i],这满足MAX-HEAPIFY(A,i)的使用条件。并且,每次循环完毕之后MAX-HEAPIFY使得i + 1, i + 2, ….., n都是最大堆的根结点,保持了循环不变量不变的特性。每次循环i的递减都重新更新了了下一次循环不变量的条件。
Maintenance: integration starts at i = ⌊n/2⌋, each loop every subtree maintain A[Parent(i)]>=A[i], this is precisely the condition required for the call MAX-HEAPIFY to make i a max-heap root. Moreover, the MAX-HEAPIFY call preserves the property that nodes i+1, i+2,…,n are all roots of max-heaps. Derementing i in the for loop update reestablishes the loop invariant for the next iteration.
(3) 结束:i=0, 结点1,2,…, n都是最大堆的根。
Termination: At Termination, i = 0, By the loop invariant,each node 1,2,…,n is the root of a max-heap.

时间复杂度分析:
从代码来看,因为MAX-HEAPIFY的时间复杂度是lgn,该函数在一个for循环中被调用,for循环的时间复杂度是n,因此综合起来就是O(nlgn), 然而这只是一个简单的运行时间上界,并非渐进紧密边界。
证明待补
结论是,BUILD-MAX-HEAP(A)的时间复杂度是O(n)

O(nlgn) is the function’s upper bound not asymptotically tight bound.
BUILD-MAX-HEAP(A) can be bounded as O(n).
2. MAX-HEAPIFY(A,i)
该函数的目的在于保持最大堆的性质。A[Parent(i)]>=A[i]。
该函数默认除了根结点之外的其他结点满足最大堆的性质。通过根结点与孩子的值不停比较使得根结点“下沉”到其应有位置。
When MAX-HEAPIFY(A,i) is called, it assumes that the binary trees rooted at LEFT(i) and Right(i) are max-heaps, but A[i] might be smaller than its children. MAX-HEAPIFY(A,i) lets the value at A[i] “float down” in the max-heap so that the subtree rooted at index i obeys the max-heap property.

算法描述:
MAX-HEAPIFY(A,i)

l = LEFT(i)
r = RIGHT(i)
if l <= A.heapsize and A[l] >= A[i]
    largest = l
    else largest = i
if r <= A.heapsize and A[l] >= A[largest]
    largest = r
if largest != i
    exchange A[largest] with A[i]
    MAX-HEAPIFY(A,largest)

这是递归描述,还可以写成循环描述。
该算法的时间复杂度为O(lgn),一个容量为n的堆,其深度为lgn,该算法的时间复杂度正比与深度。

因此,对排序算法的总体描述为

BUILD-MAX-HEAP(A)
for i = A.length downto 2
    exchange A[1] with A[i]
    A.heap-size  =  A.heap-size -1
    MAX-HEAPIFY(A,1)

具体代码实现部分待补

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值