Delete(这里理解为执行)the element with the highest / lowest priority.
二叉堆 | Binary Heap
性质
二叉堆的简单实现使用数组。首先先回顾完全二叉树,如下图。
有n个节点的完全二叉树用数组以层序储存,下标为i(1<=i<=n)的节点有如下性质。
堆序 | Heap Order
min tree:节点的值总不大于其children的值。
max tree:节点的值总不小于其children的值。
基本操作
这里均以min tree为例
Insert
/* H->Element[ 0 ] is a sentinel */
void Insert( ElementType X, PriorityQueue H )
{
int i;
if ( IsFull( H ) ) {
Error( "Priority queue is full" );
return;
}
//percolate up
for ( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 )
H->Elements[ i ] = H->Elements[ i / 2 ];
H->Elements[ i ] = X;
}
Delete
删除最小元素后,将队尾的元素移到root处,再下滤至符合要求。
ElementType DeleteMin( PriorityQueue H )
{
int i, Child;
ElementType MinElement, LastElement;
if ( IsEmpty( H ) ) {
Error( "Priority queue is empty" );
return H->Elements[ 0 ]; }
MinElement = H->Elements[ 1 ]; /* save the min element */
LastElement = H->Elements[ H->Size-- ]; /* take last and reset size */
for ( i = 1; i * 2 <= H->Size; i = Child ) { /* Find smaller child */
Child = i * 2;
if (Child != H->Size && H->Elements[Child+1] < H->Elements[Child])
Child++;
if ( LastElement > H->Elements[ Child ] ) /* Percolate one level */
H->Elements[ i ] = H->Elements[ Child ];
else break; /* find the proper position */
}
H->Elements[ i ] = LastElement;
return MinElement;
}
BulidHeap
对一个未成堆的序列,采用下滤的方式使其成堆(min tree)
只需percolate down(7), percolate down(6), percolate down(5), percolate down(4), percolate down(3), percolate down(2), percolate down(1),传入的参数为数组下标。一般地,从开始下滤。
For the perfect binary tree of height h containingnodes, 除去最后一层
个点, the sum of the heights of the nodes is
,时间复杂度为O(n)。
堆排序
堆排序的基本思想是:将待排序序列构造成一个小顶堆(min tree),此时,整个序列的最小值就是堆顶的根节点。然后执行Delete操作。再将剩余n-1个元素重新构造成一个堆,这样会得到n个元素的次小值。如此反复执行,便能得到一个有序升序列了,反之max tree可以构造降序列。时间复杂度近似为O(nlogn)。
void percolateDown(int pos) {
int X = arr[pos], i, child;
for (i = pos; i * 2 <= heapSize; i = child) {
child = i * 2;
if (child != heapSize && arr[child + 1] < arr[child]) child++;
if (arr[child] < X) arr[i] = arr[child];
else break;
}
arr[i] = X;
}
void createMinHeap() {
for (int i = heapSize / 2; i >= 1; i--) {
percolateDown(i);
}
}
void delete() {
if (heapSize == 0) return;
int min = arr[1];
int last = arr[heapSize--];
arr[1] = last;
percolateDown(1);
}
void minHeapSort() {
for (int i = 1; heapSize != 0; i++) {
sortedArr[i - 1] = arr[1];
delete();
}
}
d-Heap
对于下标为i的项,其children所在的下标为,其parent所在的下标为