堆排序:
两种堆:最大堆(A[parent(i)]>=A[i]),最小堆(A[parent(i)]<=A[i])
以下堆排序为 最大堆排序
A.length表示数组元素个数,A.heap-size表示有多少个堆元素存在该数组中
Parent(i)
return [i/2]
Left(i)
return 2i;
Right(i)
return 2i+1;
维护最大堆的重要过程:保证根节点为该子数的最大节点
Max-heapify(A,i)
l=Left(i)
r=Right(i)
if l<=A.heap-size and A[l]>A[i]
largest=l
else largest=i
if r<=A.heap-size and A[r]>A[largest]
largest=r
if largest!=i
exchange A[i] with A[largest]
Max-heapify(A,largest)
建堆-Build-Max-Heap 对其他节点都调用一次Max-heapify
Build-Max-Heap(A)
A.heap-size=A.length
for i=A[length/2] downto 1
Max-heapify(A,i)
堆排序的算法:(伪代码表示)
Heapsort(A)
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)
每一次循环中的那个A[1]即为从堆中掉出来的最大的元素,掉完以后为从达到小排序
插入排序:较小数据量时好用!
Insertion-sort(A)
for j=2 to A.length
key=A[j]
i=j-1
while i>0 and A[i]>key
A[i+1]=A[i]
i=i-1
A[i+1]=key
插入排序相当于打扑克一样
优先队列:
支持的操作包括:insert(s,x)把元素插入到集合S中;maximum(s) 返回S中具有最大关键字的元素;extract-max 去掉并返回S中的具有最大关键字的元素;increase-key:将元素x的关键字增加到key
过程Heap-Maximum可以在O(1)时间内实现Maximum操作
Heap-Maximum(A)
return A[i]
Heap-extract-Max 实现了extract-Max操作,并保持了原有的堆排序性质
Heap-Extract-Max(A)
if A.heap-size < 1
erro "heap underflow"//下溢
max=A[1]
A[1]=A[A.heap-size]
A.heap-size = A.heap-size -1
Max-heapify(A,1)
return max
更新某一节点的值
Heap-Increase- Key(A,i,key)
if key < A[i]
error "new key is smaller than current key"
A[i] = key
while i>1 and A[Parent(i)] <A [i]
exchange A[i] with A[Parent(i)]
i=Parent(i)
向堆中插入key:
A.heap-size =A .heap -size+1
A[A.heap-size]=负无穷大
Heap-Increase-key(A,A.heap-size,key)