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

C++之实现大顶堆(1)---《那些奇怪的算法》

2017-09-21 17:31 555 查看
在这篇博客中,我们利用C++编写了一个构建大顶堆的算法,其中,在删除堆元素之后的调整规为自上而下,而创建堆的时候调整算法为自下而上调整。



我们构建的大顶堆结构为:



删除掉堆顶元素之后堆的结构为:



#include <iostream>
#include <string>
using namespace std;
void swap(int& i, int& j){
int temp;
temp = i;
i = j;
j = temp;
}
int max(int i, int j){
return i > j ? i : j;
}
class Max_Queue{
public:
Max_Queue(){
}
Max_Queue(int n);
void push(int value);
int pop();
bool empty();
bool full();
void show();
~Max_Queue();
private:
int* base;
int curSize;
int capacity;
};
Max_Queue::Max_Queue(int n){
base = new int
;
capacity = n;
curSize = 0;
}
Max_Queue::~Max_Queue(){
delete[] base;
}
bool Max_Queue::empty(){
if (curSize == 0){
return true;
}
else{
return false;
}
}
bool Max_Queue::full(){
if (curSize == capacity)
return true;
else
return false;
}
void Max_Queue::push(int value){
if (full()){
cout << "该堆中元素已满,无法继续加入!!!" << endl;
return;
}
base[curSize++] = value;
int j = curSize - 1;
int i, temp;
while (j > 0){
i = (j - 1) / 2;
if (i >= 0 && base[j] > base[i]){
swap(base[j], base[i]);
j = i;
}
else{
break;
}
}
}
void Max_Queue::show(){
for (int i = 0; i < curSize; i++){
cout << base[i] << endl;
}
}
int Max_Queue::pop(){
int max_top = 0;
if (empty()){
cout << "该堆为空,无法删除元素。。。" << endl;
return -1;
}
max_top = base[0];
base[0] = base[--curSize];
int j = 0;
while (j < curSize){
int lchild = 2 * j + 1;
int rchild = 2 * j + 2;
if (lchild < curSize){
if (rchild < curSize){
int temp = max(base[lchild], base[rchild]);
if (temp > base[j]){
if (temp == base[lchild]){
swap(base[j], base[lchild]);
j = lchild;
}
else{
swap(base[j], base[rchild]);
j = rchild;
}
}
else{
break;
}
}
else{
if (max(base[lchild], base[j])>base[j]){
swap(base[lchild], base[j]);
}
break;
}
}
else{
break;
}
}
return max_top;
}
int main(){
Max_Queue mq(10);
mq.push(10);
mq.push(100);
mq.push(20);
mq.push(200);
mq.push(18);
mq.push(50);
mq.push(300);
cout << "创建的堆为:" << endl;
mq.show();
cout << "删除堆顶元素之后堆的结构:" << endl;
mq.pop();
mq.show();
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐