有些情况下,操作的数据可能带有优先级,
一般出队列时,可能需要优先级高的元素先出队列。
数据结构应该提供两个最基本的操作,
一个是返回最高优先级对象,
一个是添加新的对象。
这种数据结构就是优先级队列(Priority Queue)。
PriorityQueue底层使用了堆的数据结构,
而堆实际就是在完全二叉树的基础之上进行了一些元素的调整。
堆总是一棵完全二叉树。
如果有一个关键码的集合
K = {k0,k1, k2,…,kn-1},
把它的所有元素按完全二叉树的顺序存储方式,
存储在一 个一维数组中,
并满足:
Ki <= K2i+1 且 Ki<= K2i+2 (Ki >= K2i+1 且 Ki >= K2i+2) i = 0,1,2…,
则称为小堆(或大堆)。
将根节点最大的堆叫做最大堆或大根堆,
根节点最小的堆叫做最小堆或小根堆。
堆是一棵完全二叉树,
因此可以用 层序的规则 采用 顺序的方式 来高效存储。
对于非完全二叉树,则不适合使用顺序方式进行存储,
因为为了能够还原二叉树,空间中必须要存储空节点,
就会导致空间利用率比较低。
假设 i为节点在数组中的下标,则有:
如果 i为0,则i表示的节点为根节点。
如果 i不为0,则i节点的双亲节点为 (i - 1)/2(整数除法)。
节点i的左孩子下标为2 * i + 1 。
(如果2 * i + 1 小于节点个数没有左孩子 )
节点i的右孩子下标为2 * i + 2。
(如果2 * i + 2 小于节点个数没有右孩子)
根节点的左右子树已经完全满足堆的性质,
因此只需将根节点向下调整好即可。
向下过程(以小堆为例):
public void shiftDown(int[] array, int parent) {
// child先标记parent的左孩子,因为parent可能右左没有右
int child = 2 * parent + 1;
int size = array.length;
while (child < size) {
// 如果右孩子存在,找到左右孩子中较小的孩子,用child进行标记
if(child+1 < size && array[child+1] < array[child]){
child += 1;
}
// 如果双亲比其最小的孩子还小,说明该结构已经满足堆的特性了
if (array[parent] <= array[child]) {
break;
}else{
// 将双亲与较小的孩子交换
int t = array[parent];
array[parent] = array[child];
array[child] = t;
// parent中大的元素往下移动,可能会造成子树不满足堆的性质,因此需要继续向下调整
parent = child;
child = parent * 2 + 1;
}
}
}
找倒数第一个非叶子节点,从该节点位置开始往前一直到根节点,遇到一个节点,应用向下调整。
public static void createHeap(int[] array) {
int root = ((array.length-2) 2); //第一个非叶子节点
for (; root >= 0; root--) {
shiftDown(array, root);
}
}
// 插入新节点
public void offer(int val) {
if (isFull()) {
elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
this.elem[usedSize] = val;
usedSize++;
shiftUp(usedSize-1);
}
// 判断堆是否满了
public boolean isFull() {
return usedSize == elem.length;
}
// 向上调整
public void shiftUp(int child) {
// 找到child的双亲
int parent = (child - 1) / 2;
while (child > 0) {
// 如果双亲比孩子大,parent满足堆的性质,调整结束
if (array[parent] > array[child]) {
break;
}
else{
// 将双亲与孩子节点进行交换
int t = array[parent];
array[parent] = array[child];
array[child] = t;
// 继续向上调增
child = parent;
parent = (child - 1) / 1;
}
}
}
堆的删除一定删除的是堆顶元素。
public int pop() {
if (isEmpty()) {
return -1;
}
// 将堆顶元素与堆中最后一个元素交换
int tmp = elem[0];
elem[0] = elem[usedSize-1];
elem[usedSize-1] = tmp;
usedSize--; // 删除最后一个元素
// 重新向下调整建堆
shiftDown(0,usedSize);
return tmp; // 返回堆顶元素
}
public void heapSort() {
//1.建立大根堆 O(n)
createHeap();
//2.然后排序
int end = usedSize-1;
while (end > 0) {
int tmp = elem[0];
elem[0] = elem[end];
elem[end] = tmp;
shiftDown(0,end);
end--;
}
}