优先队列 API
Requirement. Generic items are Comparable.
1 | public class MaxPQ<Key extends Comparable<Key>> |
优先队列:无序数组实现
1 | public class UnorderedMaxPQ<Key extends Comparable<Key>> |
完全二叉树
Binary tree: Empty or node with links to left and right binary trees.
Complete tree: Perfectly balanced, except for bottom level
性质:Height of complete tree with N nodes is lg N
.
二叉树数组表示
- Indices start at 1.
- Take nodes in level order.
- No explicit links needed!
二叉树性质
- Largest key is
a[1]
, which is root of binary tree. - Can use array indices to move through tree
- Parent of node at
k
is atk/2
. - Children of node at
k
are at2k
and2k+1
.
- Parent of node at
Promotion in a heap
场景:Child’s key becomes larger key than its parent’s key
解决方案:
- Exchange key in child with key in parent.
- Repeat until heap order restored.
1 | private void swim (int k) { |
Insertion in a heap
插入:Add node at end, then swim it up.
Cost:At most 1 + lg N
compares.
1 | public void insert (Key x) { |
Demotion in a heap
场景:Parent’s key becomes smaller than one (or both) of its children’s.
解决方案:
- Exchange key in parent with key in larger child.
- Repeat until heap order restored.
1 | private void sink (int k) { |
Delete the maximum in a heap
删除最大元素:Exchange root with node at end, then sink it down.
Cost:At most 2 lg N
compares.
1 | public Key delMax() { |
完整实现
1 | public class MaxPQ<Key extends Comparable<Key>> { |
堆排序
基本步骤
构建堆
排序
Java 实现
1 | public class Heap { |
特性
总结
完全二叉堆特性
- 二叉堆中最大的节点位于
a[1]
N
个节点的完全二叉堆的高度为lg[N]
- 节点
k
的父节点为k/2
- 几点
k
的子节点为2k
和2k+1
主要实现
1 | public class MaxPQ<Key extends Comparable<Key>> |