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

来源:互联网 发布:golang test用法 编辑:程序博客网 时间:2024/06/08 18:10

在这篇博客中,我们利用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[n];    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;}

运行结果:
这里写图片描述

阅读全文
0 0