最大堆及优先队列的实现

来源:互联网 发布:python 手写识别 编辑:程序博客网 时间:2024/05/22 03:11

最大堆的原理与实现比较简单,只需要用数组即可实现,下面给出我的实现版本

对于向上调整函数,向下调整函数的实现,我运用递归的方法。

/*最大堆的实现(以int型为例)成员函数:一、向下调整函数void MaxHeapSiftDown(MAX_HEAP &h, int i)功能:将堆h中第i个元素向下调整二、向上调整函数void MaxHeapSiftUp(MAX_HEAP &h, int i)功能:将堆h中第i个元素向上调整三、弹出堆顶元素函数void MaxHeapPop(MAX_HEAP &h)功能:将堆h中最大元素删除四、返回堆顶元素函数int MaxHeapTop(MAX_HEAP h)功能:返回堆h中的最大元素五、插入函数void MaxHeapPush(MAX_HEAP &h, int value)功能:将值为value的元素插入堆h中*/#include <iostream>#include <cstdio>#include <cstdlib>using namespace std;const int maxn = 10000;const int inf = 100000;struct MAX_HEAP {int heap[maxn];int size;}h;void MaxHeapSiftDown(MAX_HEAP &h, int i){int pos = i;int L = 2 * i;int R = 2 * i + 1;if (L <= h.size && h.heap[L] > h.heap[pos])pos = L;if (R <= h.size && h.heap[R] > h.heap[pos])pos = R;if (pos != i) {swap(h.heap[pos], h.heap[i]);MaxHeapSiftDown(h, pos);}}void MaxHeapSiftUp(MAX_HEAP &h, int i){if (i > 1 && h.heap[i] > h.heap[i/2]) {swap(h.heap[i], h.heap[i/2]);MaxHeapSiftUp(h, i / 2);}}void MaxHeapPush(MAX_HEAP &h, int value){    h.size++;    h.heap[h.size] = value;    MaxHeapSiftUp(h, h.size);}int MaxHeapTop(MAX_HEAP h){    if (h.size >= 1)        return h.heap[1];    else {        fprintf(stderr, "none element\n");        return -inf;    }}void MaxHeapPop(MAX_HEAP &h){    if (h.size >= 1) {        h.heap[1] = h.heap[h.size];        h.size--;        MaxHeapSiftDown(h, 1);    } else        fprintf(stderr, "the heap is empty");    return;}int main(){    h.size = 0;    MaxHeapPush(h, 1);    MaxHeapPush(h, 8);    MaxHeapPush(h, 3);    MaxHeapPush(h, 5);    cout << MaxHeapTop(h) << endl ;    MaxHeapPop(h);    cout << MaxHeapTop(h) << endl;    MaxHeapPop(h);    MaxHeapPush(h, 11);    cout << MaxHeapTop(h) << endl;    MaxHeapPop(h);    cout << MaxHeapTop(h) << endl;    MaxHeapPop(h);return 0;}




0 0