您的位置:首页 > 编程语言 > C语言/C++

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

2017-12-07 09:00 218 查看
//构建一个堆(优先队列),采用顺序存储
//增删都是在顺序存储的尾端进行,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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 优先队列
相关文章推荐