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

来源:互联网 发布:阿里云服务器怎么设置 编辑:程序博客网 时间:2024/05/21 09:52
//构建一个堆(优先队列),采用顺序存储//增删都是在顺序存储的尾端进行,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;}