堆(优先队列)的构建以及基本操作实现

//构建一个堆(优先队列),采用顺序存储
//增删都是在顺序存储的尾端进行,push操作需要向上调整
//pop操作需要向下调整,堆的构建过程是,将构建堆所需要
//的数组顺序放在heap的连续存储空间内,然后从最尾端的
//度为2的节点开始向下调整,一直到根节点
class Heap
{
public:
    int *heap;
    int maxSize;
    int lenth;
public:
    Heap()= default;
    Heap(int size,int *a,int n);
    ~Heap();

    void shiftDown(int );
    void shiftUp(int);
    bool pop(int &);
    bool push(int );
};
Heap::~Heap()
{
    delete[] heap;
}

Heap::Heap(int size,int *a,int n)
{
    maxSize = size;
    heap = new int[size];
    lenth = n;
    for(int i =0; i<n;i++)
    {
        heap[i] = a[i];
    }
    for(int i = n/2 -1;i>=0;i++)
        shiftDown(i);

}

void Heap::shiftUp(int a)
{
    if(a > lenth - 1 || a < 0)
        return;
    int p = a;
    int uper = (a - 1)/2;
    while (uper >= 0)
    {
        if(heap[p] < heap[uper])
            return;

        int temp = heap[p];
        heap[p] = heap[uper];
        heap[uper] = temp;
        p = uper;
    }
}

void Heap::shiftDown(int a)
{
    int i = a; //标识父节点
    int j = 2*i + 1; //标识左子节点

    int temp = heap[i];
    while(j < lenth)
    {
        if((j < lenth -1) && heap[j+1]>heap[j])
            j++;
        if(temp < heap[j])
        {
            heap[i] = heap[j];
            i = j;
            j = 2*j + 1;
        }
        else break;
    }
    heap[i] = temp;
}

bool Heap::pop(int & a)
{
    if(lenth <= 0)
        return false;
    a = heap[0];
    heap[0] = heap[lenth - 1];
    lenth --;
    shiftDown(0);
    return true;
}

bool Heap::push(int a)
{
    if(lenth == maxSize)
        return false;
    heap[++lenth] = a;
    shiftUp(lenth - 1);
    return true;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值