美文网首页
binary heap

binary heap

作者: 路过的魔法师 | 来源:发表于2020-04-03 10:45 被阅读0次
max heap
#include <bits/stdc++.h>
using namespace std;

template<typename T>
class MaxPQ {
public:
    MaxPQ(int cap) {
        pq = new T[cap+1];
    }

    T max() {
        return pq[1];
    }

    void swim(int i) {
        while (i > 1 && less(parent(i), i)) {
            exchange(parent(i), i);
            i = parent(i);
        }
    }

    void sink(int i) {
        while (left(i) <= N) {
            int older = left(i);
            if (right(i) <= N && less(older, right(i))) {
                older = right(i);
            }
            if (less(older, i)) {
                break;
            }
            exchange(i, older);
            i = older;
        }
    }

    void insert(T e) {
        N++;
        pq[N] = e;
        swim(N);
    }

    T delMax() {
        T max = pq[1];
        exchange(1, N);
        pq[N] = (T)nullptr;
        N--;
        sink(1);
        return max;
    }

private:
    T* pq = nullptr;
    int N = 0;          // N is current size not capability

    bool less(int i, int j) {
        return pq[i] < pq[j];
    }

    void exchange(int i, int j) {
        T tmp = pq[i];
        pq[i] = pq[j];
        pq[j] = tmp;
    }

    int parent(int root) {
        return root / 2;
    }

    int left(int root) {
        return root * 2;
    }

    int right(int root) {
        return root * 2 + 1;
    }
};

int main(void) {
    MaxPQ<int> pq(10);
    pq.insert(3);
    cout << pq.max() << endl;
    pq.insert(5);
    cout << pq.max() << endl;
    pq.insert(1);
    cout << pq.max() << endl;
    pq.delMax();
    cout << pq.max() << endl;
    pq.delMax();
    cout << pq.max() << endl;

    cout << endl;
}
3
5
5
3
1

感谢大二数据结构课偷偷瞄了几眼严奶奶的书。
通过上浮和下沉操作维护二叉堆性质,至于为啥分上浮和下沉,我觉得可能是出于方便insertdelete的考虑,insert插到堆底一直上浮就行,delete呢,算法设计得很妙,堆顶下沉方便,堆底上浮方便,删堆顶只要交换堆顶堆底并下沉当前堆顶即可维护二叉堆性质。

相关文章

  • 10. Heapsort and Priority Queues

    Heaps A binary heap is a nearly complete binary tree with...

  • binary heap

    感谢大二数据结构课偷偷瞄了几眼严奶奶的书。通过上浮和下沉操作维护二叉堆性质,至于为啥分上浮和下沉,我觉得可能是出于...

  • 11.Hedp(堆)

    概念: 堆(Heap)亦被称为:优先队列(priority queue)Binary Heap is a comm...

  • 2020-07-14(堆)

    定义:Heap is a binary tree with two special properties: it ...

  • 《恋上数据结构与算法一》笔记(十六)堆

    目录 问题思考 Top K问题 堆(Heap) 堆的基本接口设计 二叉堆(Binary Heap) 获取最大值 最...

  • 堆 Heap、二叉堆 Binary Heap

    堆 Heap 堆是计算机科学中的一种特别的树状数据结构。 定义:给定堆中任意节点 P 和 C,若 P 是 C 的母...

  • 二叉堆

    二叉堆(Binary Heap) 本文相关代码参见 Algorithms/BinaryHeap 定义 二叉堆本质上...

  • 二叉堆(Binary Heap)

    什么是二叉堆 二叉堆是一颗特殊的二叉树(完全二叉树) 父节点一定都不大于左右节点(小顶堆) 树的每一层都从左到右一...

  • 二叉堆(Binary Heap)

    二叉堆这个数据结构有点意思,自己做了个总结,内容结构如下: 二叉堆性质 二叉堆操作 应用 二叉堆性质: 堆(Hea...

  • 堆/二分搜索树/图

    最大堆 heap sort 二分搜索 binary sort 二分搜索树 并查集union find 基于size...

网友评论

      本文标题:binary heap

      本文链接:https://www.haomeiwen.com/subject/imvcphtx.html