堆节点的访问
通常堆是通过一维数组来实现的。在起始数组为 0 的情形中:
- 父节点i的左子节点在位置 (2*i+1);
- 父节点i的右子节点在位置 (2*i+2);
- 子节点i的父节点在位置 floor((i-1)/2);
堆的操作
在堆的数据结构中,堆中的最大值总是位于根节点。堆中定义以下几种操作:
- 最大堆调整(Max_Heapify):将堆的末端子结点作调整,使得子结点永远小于父结点
- 创建最大堆(Build_Max_Heap):将堆所有数据重新排序
- 堆排序(HeapSort):移除位在第一个数据的根结点,并做最大堆调整的递归运算
![](https://www.evernote.com/shard/s292/res/62684697-8146-472f-ae7e-9a12fca6b9bd.png?resizeSmall&width=785)
Bottom-up reheapify ( swim).
private void sink(int k)
{
while (2*k <= N){
int j = 2*k;if (j < N && less(j, j+1)) j++;if (!less(k, j)) break;exch(k, j);k = j;
}
}
![](https://www.evernote.com/shard/s292/res/409f4969-91d7-4f4f-b113-7d3d5b813bf6.png?resizeSmall&width=785)
Bottom-up reheapify ( swim).
private void swim(int k)
{
while (k > 1 && less(k/2, k)){
exch(k/2, k);k = k/2;
}
}
![](https://www.evernote.com/shard/s292/res/58b208dd-de46-4661-8fd0-b084b98248b8.png?resizeSmall&width=785)
private boolean less(int i, int j)
{ return pq[i].compareTo(pq[j]) < 0; }
private void exch(int i, int j)
{ Key t = pq[i]; pq[i] = pq[j]; pq[j] = t; }
ALGORITHM 2.6 Heap priority queue
public class MaxPQ<Key extends Comparable<Key>>
{
private Key[] pq; // heap-ordered complete binary tree
private int N = 0; // in pq[1..N] with pq[0] unused
public MaxPQ(int maxN)
{ pq = (Key[]) new Comparable[maxN+1]; }
public boolean isEmpty()
{ return N == 0; }
public int size()
{ return N; }
public void insert(Key v)
{
pq[++N] = v;swim(N);
}
public Key delMax()
{
Key max = pq[1]; // Retrieve max key from top.exch(1, N--); // Exchange with last item.pq[N+1] = null; // Avoid loitering.sink(1); // Restore heap property.return max;
}
// See pages 145-147 for implementations of these helper methods.
private boolean less(int i, int j)
private void exch(int i, int j)
private void swim(int k)
private void sink(int k)
}