树_最小堆

以下是最小堆添加节点和删除最小节点的功能实现。

特点:

A.完全二叉树(降低高度)。
B.充分利用数组存储,通过下标可以直接找到父子关系。
C.插入新元素和/删除最小元素不需要大量移动,最坏只需要进行logN次重新调整即可。
D.获取最小值时间复杂度O(1)。
E.操作过程适合实现优先队列。
F.堆排序时间复杂度O(NlogN)。


class Heap
{
public:
    typedef int key_t;
    Heap(size_t max = 64);
    ~Heap();

    key_t GetMin();
    bool Add(key_t key);
    bool RemoveMin();
    
private:
    size_t _max;
    size_t _count;
    key_t *_nodes;
};


Heap::Heap(size_t max) : _max(max),_count(0),_nodes(NULL)
{
    if (_max)
        _nodes = new key_t[_max+1];
}

Heap::~Heap()
{
    if (_nodes)
        delete []_nodes;
}

Heap::key_t Heap::GetMin()
{
    return _count > 0 ? _nodes[1] : numeric_limits<int>::min();
}

bool Heap::Add(key_t key)
{
    int curIndex;
    
    if (_count < _max) {
        _nodes[++_count] = key;
        curIndex = _count;

        while(curIndex > 1) {
            if(_nodes[curIndex] < _nodes[curIndex/2]) {
                key_t tmp = _nodes[curIndex/2];
                _nodes[curIndex/2] = _nodes[curIndex];
                _nodes[curIndex] = tmp;
                curIndex /= 2;
            } else {
                return true;
            }
        }
    } else {
        cout<<"===>Can't be inserted, limit to maxmium!"<<endl;
        return false;
    }
    return true;
}

bool Heap::RemoveMin()
{
    if (_count) {
        size_t curIndex = 1, min;
        _nodes[1] = _nodes[_count--];
        while(2*curIndex <= _count) {
            min = 2*curIndex;
            if (2*curIndex+1 <= _count) {
                min = _nodes[2*curIndex] < _nodes[2*curIndex+1] ? 2*curIndex : 2*curIndex+1;
            } 

            if (_nodes[curIndex] > _nodes[min]) {
                key_t tmp = _nodes[curIndex];
                _nodes[curIndex] = _nodes[min];
                _nodes[min] = tmp;
                curIndex = min;
            } else {
                return true;
            }
        }

        return true;
    }

    cout<<"===>Can't be removed, heap is already empty!"<<endl;
    return false;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值